Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string by top-most level parentheses

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.

like image 534
Giora Guttsait Avatar asked Aug 30 '25 18:08

Giora Guttsait


1 Answers

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);
like image 76
Anna Fohlmeister Avatar answered Sep 02 '25 07:09

Anna Fohlmeister