Regex - Match every comma NOT between delimiters

Viewed 76

This seems to be a frequent kind of question here on StackOverflow, but I couldn't get it working properly. Apologies for any inconvenience.

I need to split a string for every comma found outside of a group delimited by pairs of dollar signs. I'm using Javascript.

Expected behavior: "$g=9,8m/s$, p,q, $m=19,0$, banana"

Should return ["$g=9,8m/s$", "p", "q", "$m=19,0$", "banana"]


Ideally, dollar signs prefixed by \ should be ignored as follows:

"$$g=9,8m/s$$, p,q, $price=\$19,0$, banana"

Returns ["$$g=9,8m/s$$", "p", "q", "$price=\$19,0$", "banana"]

But for now I'm happy without this feature.


My best attempt was (\$[^\$]*\$)|[^,]+

Which matches just the first group, returning: ["$g=9,8m/s$", "p", "q", "$m=19", "0$, "banana"]

What am I getting wrong here? Appreciate your help!

1 Answers

You may use

s.match(/\$+[^$\\]*(?:\\[\s\S][^$\\]*)*\$+|[^,\s][^,]*/g)

See the regex demo

Details

  • \$+[^$\\]*(?:\\[\s\S][^$\\]*)*\$+ - one or more $ chars followed with any 0 or more chars other than $ and \, followed with 0 or more repetitions of a \ and then any single char and then 0 or more chars other than \ and $, and then 1 or more $s
  • | - or
  • [^,\s][^,]* - any char other than comma and whitespace and then any 0 or more chars other than a comma.
Related