正则表达式用空格分割字符串,考虑嵌套括号 [英] 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)
进入:
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)
但是这给了我:
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...
推荐答案
这是我的解决方案:
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;
}
这篇关于正则表达式用空格分割字符串,考虑嵌套括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文