Home > Mobile >  Split string by space but exclude inside parentheses or balanced brackets
Split string by space but exclude inside parentheses or balanced brackets

Time:06-17

I have this expression:

"( ( User01 And User02 ) Or User03 ) And ( User04 OR User05 OR [GROUPX] ) And User07 And User08"

And I want to break it up into these parts:

"( ( User01 And User02 ) Or User03 )"
"AND"
"( User04 OR User05 OR [GROUPX] )"
"And"
"User07"
"And"
"User08"

I have used the following regular expression:

/(\S @\S )|\OR|\AND|(\(. ?\))|(\[. ?\])/g 

But it does not give me the expected results. How can I make it work?

CodePudding user response:

You'd need recursion, but JavaScript's regular expressions don't have support for recursion. So create a simple parser that breaks down the string into words, and then keeps track of the depth of nesting parentheses. Collect the words, and each time that depth is 0, output (and clear) that collection:

function parse(s) {
    let depth = 0;
    const collect = [];
    const result = [];
    
    for (let token of s.split(" ")) {
        depth  =  (token === "(") -  (token === ")");
        collect.push(token);
        if (depth === 0) {
            result.push(collect.join(" "));
            collect.length = 0;
        }
    }
    return result;
}

// Example run:
const s = "( ( User01 And User02 ) Or User03 ) And ( User04 OR User05 OR [GROUPX] ) And User07 And User08";
const result = parse(s);
console.log(result);

  • Related