Repeated Javascript expression for exception if inside brackets

I am trying to split the expression string into + * () characters, but I only need to split it if they are not inside the brackets. I am trying to create the correct regular expression for this task.

Example:

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

I would like this to create an array, for example:

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

Currently, my regex is broken into + * () [] characters

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

Since I also broke into square brackets, I then iterate over the array and concatenate something inside the brackets. I think this is awkward, and I would like to move all this into a regular expression.

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 use JavaScript and need support to support IE8. I also read something about being able to do this with a negative look, but I saw that JavaScript does not support this.

+4
1

.N.TEST[INT1+2] + ON[INT1] * ON[INT2]? regex .

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

[... ]

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

JSFiddle demo

+3

Source: https://habr.com/ru/post/1607481/


All Articles