I have a string like the following: '(1) (2 (3))'
I want to regex it to get the following array: ['1', '2 (3)']
another example: '(asd (dfg))(asd (bdfg asdf))(asd)'
-> ['asd (dfg)', 'asd (bdfg asdf)', ('asd')]
I've tried to search how to do such a regex, but I've only found ones that split by all the ()
, couldn't find anything to only filter the highest level of them.
I don't see a way to resolve it with regex, here's a programmatic approach (although there are probably a lot more elegant ways to approach this issue ... particularly as it is very fragile, it relies on the parentheses to always be applied in the correct order).
var string = "(asd (dfg))(asd (bdfg asdf))(asd)".split(''),
result = [],
fragment = '',
countOpen = 0,
countClosed = 0;
string.forEach(function (character) {
fragment += character;
if (character === '(') {
countOpen += 1;
}
if (character === ')') {
countClosed += 1;
if (countOpen === countClosed) {
result.push(fragment.slice(1, -1));
fragment = '';
}
}
});
console.log(result);
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