Search code examples
javascriptregexnegative-lookbehind

Javascript regex to exclude if inside brackets


I'm trying to split an expression string on the characters +*() but I need to only split there if they are not inside brackets. I am struggling to create the correct regex for this task.

Example:

.N.TESTARRAY[INT1+2] + ONLINE * STACKOVERFLOW

I would like this to produce an array such as:

[ ".N.TESTARRAY[INT1+2]" , "ONLINE" , "STACKOVERFLOW" ]

Currently my regex splits on the characters +*()[]

split(/(\+|\*|\[|\]|\(|\))/g)

Because I split on the square brackets as well, I then loop through the array and merge anything inside the brackets. I think this is clunky though and would like to move it all into the regex.

function mergeInnerBrackets(tokens) {
        var merged = [];
        var depth = 0;

        for(var i = 0; i < tokens.length; i++) {
            if(tokens[i] == "[") {
                depth++;
                merged[merged.length-1] += "[";
            } else if(tokens[i] == "]") {
                depth--;
                merged[merged.length-1] += "]";
            } else if(depth > 0) {
                merged[merged.length-1] += tokens[i];
            } else {
                merged.push(tokens[i]);
            }
        }

        return merged;
}

I am using JavaScript and need to be able to support back to IE8. I also read something about being able to do this with negative-look behinds but I saw that JavaScript doesn't support that.


Solution

  • Can string also be like .N.TEST[INT1+2] + ON[INT1] * ON[INT2] ? I'd rather use regex like this.

    \s*[+*)(](?![^[]*])\s*
    

    If the string can contain more than one pair of [...]

    var str = '.N.TEST[INT1+2] + ON[INT1] * ON[INT2]';
    console.log(str.split(/\s*[+*)(](?![^[]*])\s*/));
    

    JSFiddle demo