I'm trying to split a sentence by whitespace/space but I must exclude space located inside parenthesis ()
, accolades {}
or squared brackets []
.
我试图用空格/空格分割一个句子,但我必须排除位于括号(),荣誉{}或方括号[]内的空格。
ex string: [apples carrots] (car plane train) {food water} foo bar
should result in an array containing:
ex string:[苹果胡萝卜](汽车飞机列车){food water} foo bar应该产生一个包含以下内容的数组:
- [apples carrots]
- (car plane train)
- {food water}
- foo
- bar
(汽车飞机列车)
Any ideas?
3 个解决方案
#1
2
Split on whitespace followed by a positive look-ahead that checks if next bracket char (if any) is an open one (or end of input):
在空格上拆分,然后是正向前瞻,检查下一个括号char(如果有)是否为打开的(或输入结束):
\s+(?=[^\])}]*([\[({]|$))
#2
3
Not splitting, but matching and trimming. Example is in JavaScript, you can try it out in browser console:
不分裂,但匹配和修剪。示例是在JavaScript中,您可以在浏览器控制台中尝试:
var a = '[apples carrots] (car plane train) {food water} foo bar';
a.match(/[a-zA-Z0-9\[\]\(\){}]+/g).map(function (s) { return s.replace(/[\[\]\(\)\{\}]/, ''); });
["apples", "carrots", "car", "plane", "train", "food", "water", "foo", "bar"]
Alternatively:
a.split(/\s+(?![^\[]*\]|[^(]*\)|[^\{]*})/)
Produces:
["[apples carrots]", "(car plane train)", "{food water}", "foo", "bar"]
#3
0
to match the space outside (), {} and [] use this pattern (\s)(?:(?=(?:(?![\]\)}]).)*[\[\({])|(?!.*[\]\)}]))
Demo
匹配外部空间(),{}和[]使用此模式(\ s)(?:(?=(?:(?![\] \)}])。)* [\ [\({] )|(?!。* [\] \)}]))演示
#1
2
Split on whitespace followed by a positive look-ahead that checks if next bracket char (if any) is an open one (or end of input):
在空格上拆分,然后是正向前瞻,检查下一个括号char(如果有)是否为打开的(或输入结束):
\s+(?=[^\])}]*([\[({]|$))
#2
3
Not splitting, but matching and trimming. Example is in JavaScript, you can try it out in browser console:
不分裂,但匹配和修剪。示例是在JavaScript中,您可以在浏览器控制台中尝试:
var a = '[apples carrots] (car plane train) {food water} foo bar';
a.match(/[a-zA-Z0-9\[\]\(\){}]+/g).map(function (s) { return s.replace(/[\[\]\(\)\{\}]/, ''); });
["apples", "carrots", "car", "plane", "train", "food", "water", "foo", "bar"]
Alternatively:
a.split(/\s+(?![^\[]*\]|[^(]*\)|[^\{]*})/)
Produces:
["[apples carrots]", "(car plane train)", "{food water}", "foo", "bar"]
#3
0
to match the space outside (), {} and [] use this pattern (\s)(?:(?=(?:(?![\]\)}]).)*[\[\({])|(?!.*[\]\)}]))
Demo
匹配外部空间(),{}和[]使用此模式(\ s)(?:(?=(?:(?![\] \)}])。)* [\ [\({] )|(?!。* [\] \)}]))演示