-5

Let's say I have the data string (to make it easier: assuming only alphanumeric characters can occur as values, no quotation marks or empty slots):

[12365, blah, 458, hello, 99996332]

I have looked at Regex for Comma delimited list and best I could find was the regex

(.+?)(?:,|$)

... which results with 5 matches in group 1 in https://regex101.com/:

regex101

However, those also contain the string "delimiters", if you will - that is, the [ and the ] - in the matches.

SO, I thought I'd add the [ and the ] as a literal match, so I can avoid them interfering with the rest - I used the regex:

\[(.+?)(?:,|$)\]

... but this results with 0 matches.

So, what javascript regex can I use, to "ignore" start and end delimiters of a string, and otherwise capture/match all comma-separated entries inside the start and end delimiters of the string?

sdbbs
  • 4,270
  • 5
  • 32
  • 87
  • 1
    With your examples, you might as well use `text.match(/\w+/g)`. Of course, you can make it more complicated with `text.match(/[^\][,\s][^\][,]*/g)`, but even then it is just guessing. If the text values get literal commas inside them, this becomes impossible. You should ask the data provider to fix this on their end. – Wiktor Stribiżew Jul 10 '23 at 13:52
  • [Hundreds if not thousands of answers](https://www.google.com/search?q=site%3Astackoverflow.com+parse+csv) – mplungjan Jul 10 '23 at 14:02
  • Perhaps you want `.slice(1, -1)`? – InSync Jul 10 '23 at 14:11
  • The `\[` at beginning and `\]` at the end won't match anything. It requires they be there on every match. While the first `\[` will match at the beginning, the last `\]` can only ever match with a comma before it. If the goal is to match everything while keeping the fields a separate group, this is the best bet `(?:(?!^)|^\[)\s*(.*?)\s*(?:,|\]$)` https://regex101.com/r/90MUOT/1 (has trim) – sln Jul 10 '23 at 22:57

1 Answers1

0

You could substring the data first.

var string = '[12365, blah, 458, hello, 99996332]'
string = string.substring(1, string.length - 1)

Although, I guess you could technically use the following pattern.

\[?(.+?)(?:, |\])

Additionally, you can use the split function to return an array of values.

var string = '[12365, blah, 458, hello, 99996332]'
string = string.substring(1, string.length - 1)
var strings = string.split(', ')

console.log(strings)
Reilas
  • 3,297
  • 2
  • 4
  • 17