繁体   English   中英

正则表达式考虑到嵌套括号将字符串按空格分割

[英]Regex split string by spaces taking into account nested brackets

我知道这个问题已经被问过/回答过几次,但是不幸的是,到目前为止,我尝试过的所有解决方案都无法解决我的问题。 我需要这样分割:

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

通过遵循此解决方案 ,我目前正在这样做:

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

因为正则表达式不能捕获所有的右括号...

这是我的解决方案:

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

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

 function splitOnWhitespaceOutsideBalancedParens() { var item = '', result = [], stack = 0, whitespace = /\\s/; for (var i=0; i < text.length; i++) { if ( text[i].match(whitespace) && stack == 0 ) { result.push(item); item = ''; continue; } else if ( text[i] == '(' ) { stack++; } else if ( text[i] == ')' ) { stack--; } item += text[i]; } result.push(item); return result; } var text = "contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)"; console.log(splitOnWhitespaceOutsideBalancedParens(text)); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM