正则表达式用空格分割字符串,考虑嵌套括号

时间:2017-06-07 06:37:00

标签: javascript regex

我知道这已被多次提出/回答,但不幸的是,到目前为止,我所尝试过的解决方案都没有。 我需要拆分这样的东西:

contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)

进入这个:

contrast(200%)
drop-shadow(0px 0px 10px rgba(0,0,0,.5))

通过关注this solution,我目前正在这样做:

myString = "contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)"
myString.match(/[^\(\s]+(\(.*?\)+)?/g)

但是这给了我:

contrast(200%)
drop-shadow(rgba(0, 0, 0, 0.5)  <== notice the missing second ) here
0px    <== unwanted, should go with previous one
0px    <== unwanted, should go with previous one
10px)  <== unwanted, should go with previous one

因为正则表达式没有捕获所有结束括号......

2 个答案:

答案 0 :(得分:2)

这是我的解决方案:

function splitBySpaces(string){
    var openBrackets = 0, ret = [], i = 0;
    while (i < string.length){
        if (string.charAt(i) == '(')
            openBrackets++;
        else if (string.charAt(i) == ')')
            openBrackets--;
        else if (string.charAt(i) == " " && openBrackets == 0){
            ret.push(string.substr(0, i));
            string = string.substr(i + 1);
            i = -1;
        }
        i++;
    }

    if (string != "") ret.push(string);
    return ret;
}

答案 1 :(得分:1)

您可以使用以下代码在嵌套括号外的空格/制表符上拆分字符串:

&#13;
&#13;
export default
&#13;
&#13;
&#13;