Split string into top-level brackets

I have a line 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 tried to find how to do such a regex, but I only found the ones that were split into all ()

, couldn't find anything to filter out their highest level.

+3


source to share


1 answer


I don't see a way to resolve it with regex, here's a programmatic approach (although there are probably much more elegant ways to approach this problem ... especially since it's very fragile, it relies on 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);
      

Run codeHide result


+1


source







All Articles