除了括号中的空格之外的所有空格拆分字符串 [英] Split string by all spaces except those in brackets
问题描述
可能重复:
根据正则表达式拆分字符串
我'从来没有成为正规表达大师,所以我需要你的帮助!我有一个这样的字符串:
I've never been a regular expression guru, so I need your help! I have a string like this:
String s = "a [b c] d [e f g]";
我想用空格分隔这个字符串作为分隔符 - 但我不想拆分出现在 []
括号内的空格。所以,从上面的例子中,我想要这个数组:
I want to split this string using spaces as delimiters -- but I don't want to split on spaces that appear within the []
brackets. So, from the example above, I would like this array:
{"a", "[b c]", "d", "[e f g]"}
有关正则表达式可以与<$一起使用的任何建议c $ c>拆分以实现这个目标?
Any advice on what regex could be used in conjunction with split
in order to achieve this?
这是另一个例子:
"[a b] c [[d e] f g]"
变为
{"[a b]", "c", "[[d e] f g]"}
推荐答案
我认为这是应该工作,使用否定前瞻 - 它不匹配没有开口的关闭括号之前的空格括号:
I think this should work, using negative lookahead - it matches no whitespace that comes before closing bracket without an opening bracket:
"a [b c] d [e f g]".split("\\s+(?![^\\[]*\\])");
对于嵌套括号,你需要编写一个解析器,正则表达式无法承受无限级别并得到超过一个或两个级别太复杂了。例如,我的表达式失败
For nested brackets you will need to write a parser, regexes can't afford an infinite level and get too complicated for more than one or two levels. My expression for example fails for
"[a b [c d] e] f g"
这篇关于除了括号中的空格之外的所有空格拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!