Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore comma within nested parentheses for a Regex match

Tags:

regex

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.

like image 700
Temani Afif Avatar asked Dec 05 '25 01:12

Temani Afif


1 Answers

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.
like image 121
Wiktor Stribiżew Avatar answered Dec 10 '25 07:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!