-1

I need to write a regex to target commas that exist only outside a pair of brackets or braces.

Currently I have:

var regex = /,(?![^{]*})(?![^[]*])/g

When the target string is:

var str = '"a":[{"b":2,"c":["d"]}],"b":2'    // OK: only second comma matches

the pattern correctly matches only the second comma.

When the target string is:

var str = '"a":[{"b":2,"c":{"d":9}}],"b":2'    // OK: only second comma matches

the pattern also correctly matches only the second comma.

However, when the target string includes a array and object, the negative lookahead fails and the regex matches both commas.

var str = '"a":[{"b":2,"c":[{"d":9}]}],"b":2'    // BAD: both commas match
RhinoDavid
  • 750
  • 5
  • 9

1 Answers1

0

This regex will work (see demo) with the mentioned example:

,(?!([^{]*{[^{]*})?[^{]*})(?!([^[]*\[[^[]*])?[^[]*])

But it's not a generic regex.

For each level of nested brackets you need to expand the regex. For example, to match also "a":[{"b":2,"c":[{"d":[{"e":9}]}]}],"b":2 you will need:

,(?!([^{]*{([^{]*{[^{]*})?[^{]*})?[^{]*})(?!([^[]*\[([^[]*\[[^[]*])?[^[]*])?[^[]*])

See second demo.

This is not a scalable solution, but it's the only one with regexes. Just for curiosity.

horcrux
  • 4,954
  • 5
  • 24
  • 35