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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With