我有一个字符串,需要用空格分割它,但如果括号内有一些单词,我需要跳过它。
例如,
input: 'tree car[tesla BMW] cat color[yellow blue] dog'
output: ['tree', 'car[tesla BMW]', 'cat', 'color[yellow blue]', 'dog']
Run Code Online (Sandbox Code Playgroud)
如果我使用 simple ,.split(' ')它会进入括号内并返回不正确的结果。
另外,我试图写一个正则表达式,但没有成功:(
我的最后一个正则表达式看起来像这样.split(/(?:(?<=\[).+?(?=\])| )+/)并返回["tree", "car[", "]", "cat", "color[", "]", "dog"]
非常感谢您的帮助
这更容易match:
input = 'tree car[tesla BMW] cat xml:cat xml:color[yellow blue] dog'
output = input.match(/[^[\]\s]+(\[.+?\])?/g)
console.log(output)Run Code Online (Sandbox Code Playgroud)
有了split你需要这样的前瞻:
input = 'tree car[tesla BMW] cat color[yellow blue] dog'
output = input.split(/ (?![^[]*\])/)
console.log(output)Run Code Online (Sandbox Code Playgroud)
这两个片段仅在括号未嵌套时才有效,否则您需要解析器而不是正则表达式。