2

I have the following Regex /[^,\s]+(?:\s+\([^)]*\))?/g that allows me to match elements separated by a comma while ignoring the commas inside ()

Having this:

a,b,c (aaa, bbb, ccc),d

I get this

a
b
c (aaa, bbb, ccc)
d

Now, I want to upgrade it to consider another level of parentheses. I don't want to consider any level (I know recursive is not possible) but only 2 level max.

Having this:

a,(b, b),c (aaa, (bbb, cccc, ddd)),d

I need to get

a
(b, b)
c (aaa, (bbb, cccc, ddd))
d

I am using https://regex101.com/ for testing if that helps.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415

1 Answers1

2

You can use

const matches = text.match(/(?:\([^()]*(?:\([^()]*\)[^()]*)*\)|[^,])+/g);

See the regex demo.

The regex matches one or more repetitions of

  • \([^()]*(?:\([^()]*\)[^()]*)*\) - a ( + zero or more chars other than parentheses + zero or more repetitions of a substring between parentheses followed with zero or more chars other than parentheses + a ) char (substring between max two-level nested parentheses)
  • | - or
  • [^,] - a char other than a comma.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563