[英]Regex split string by spaces taking into account nested brackets
I know that this has been asked/answered several times but unfortunately none of the solutions I've tried so far works in my case. 我知道这个问题已经被问过/回答过几次,但是不幸的是,到目前为止,我尝试过的所有解决方案都无法解决我的问题。 I need to split something like this: 我需要这样分割:
contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)
into this: 到这个:
contrast(200%)
drop-shadow(0px 0px 10px rgba(0,0,0,.5))
By following this solution , I'm currently doing this: 通过遵循此解决方案 ,我目前正在这样做:
myString = "contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)"
myString.match(/[^\(\s]+(\(.*?\)+)?/g)
but this gives me: 但这给了我:
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
as the regexp does not capture all closing brackets... 因为正则表达式不能捕获所有的右括号...
Here is my solution: 这是我的解决方案:
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;
}
You may split a string on spaces/tabs that are outside of nested parentheses using the code below: 您可以使用以下代码在嵌套括号之外的空格/制表符上拆分字符串:
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.