This is a direct follow up of my previous question where I got the following Regex;
const matches = text.match(/(?:\([^()]*(?:\([^()]*\)[^()]*)*\)|[^,])+/g);
From this a,(b, b),c (aaa, (bbb, cccc, ddd)),d
I get
a
(b, b)
c (aaa, (bbb, cccc, ddd))
d
But it fails when I have the following case a,(b, b),c (aaa, ((b b), cccc, ddd)),d
where there are 3 nested parentheses which is logical after dissecting how the Regex works.
I tried to update it to consider another level of parentheses and I did the following
const matches = text.match(/(?:\([^()]*(?:\([^()]*(?:\([^()]*\)[^()]*)*\)[^()]*)*\)|[^,])+/g)
It works (online demo) but I am not sure if it's the optimal solution. I also don't know if it will cover all the cases. Can anyone confirm? or maybe there is a better Regex.
I am also looking for a way to generate such Regex for a giving number of parentheses. I have it for 2 and 3 but what about N? Will it work if I always repeat the following part (?:\([^()]*\)[^()]*)*
recursively? I know Regex cannot handle any number of nested parentheses but I am not looking for this. I want for a giving number to generate the regex (using JS) and use it.