按空格拆分字符串但不在括号内 [英] Split string by whitespace but not within brackets
本文介绍了按空格拆分字符串但不在括号内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的字符串 foo bar(5)baz(0,3)
,需要根据每个字符串之间的空格将其拆分成部分。所以结果需要如下所示: ['foo','bar(5)','baz(0,3)']
。
I've a string like this foo bar(5) baz(0, 3)
and need to split it into its parts based on spaces between each. So the result needs to look like this: ['foo', 'bar(5)', 'baz(0, 3)']
.
我尝试过这样的事情:
var str = 'foo bar(5) baz(0, 3)';
str.split(' '); // => ['foo', 'bar(5)', 'baz(0,', '3)']
正如你所看到的结果不是我所期望的......任何想法如何正确分割它?我认为这是 RegExp
-gurus的转折......
As you can see the result is not what I expect... Any ideas how to split it correctly? I think it's a turn for the RegExp
-gurus here...
更新
一种简单的方法可以用替换所有
:,
,
A simple way could be to replace all ,
with ,
:
str.replace(/, /g, ',').split(' ');
但这对我来说看起来不太好......
But that doesn't look really pretty to me...
推荐答案
您可以使用 .match
。
str.match(/\w+(\(.*?\))?/g)
=> ["foo", "bar(5)", "baz(0, 3)"]
这篇关于按空格拆分字符串但不在括号内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文