split string by top-most level parentheses

依然范特西╮ 提交于 2021-02-10 03:42:00

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/43310832/split-string-by-top-most-level-parentheses

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!