按除括号外的所有空格分割字符串 [英] Split string by all spaces except those in parentheses
本文介绍了按除括号外的所有空格分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图像在空格上分割文本如下:
I'm trying to split text the following like on spaces:
var line = "Text (what is)|what's a story|fable called|named|about {Search}|{Title}"
但是我希望它忽略括号内的空格.这应该产生一个具有以下内容的数组:
but I want it to ignore the spaces within parentheses. This should produce an array with:
var words = ["Text", "(what is)|what's", "a", "story|fable" "called|named|about", "{Search}|{Title}"];
我知道这应该涉及带有line.match()的某种正则表达式.如果正则表达式删除括号,则加分.我知道word.replace()将在后续步骤中摆脱它们.
I know this should involve some sort of regex with line.match(). Bonus points if the regex removes the parentheses. I know that word.replace() would get rid of them in a subsequent step.
推荐答案
对特定的正则表达式模式使用以下方法(基于负超前断言):
Use the following approach with specific regex pattern(based on negative lookahead assertion):
var line = "Text (what is)|what's a story|fable called|named|about {Search}|{Title}",
words = line.split(/(?!\(.*)\s(?![^(]*?\))/g);
console.log(words);
-
(?!\(.*)
确保分隔符\ s
前没有大括号(
(包括伴随字符) -
(?![^(] *?\))
确保分隔符\ s
后没有大括号)
(包括服务员角色)
(?!\(.*)
ensures that a separator\s
is not preceded by brace(
(including attendant characters)(?![^(]*?\))
ensures that a separator\s
is not followed by brace)
(including attendant characters)
这篇关于按除括号外的所有空格分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文