使用正则表达式跳过括号[]拆分字符串

我有一个字符串,需要用空格分割它,但如果括号内有一些单词,我需要跳过它。

例如,

input: 'tree car[tesla BMW] cat color[yellow blue] dog'

output: ['tree', 'car[tesla BMW]', 'cat', 'color[yellow blue]', 'dog']

如果我使用 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)

有了split你需要这样的前瞻:

input = 'tree car[tesla BMW] cat color[yellow blue] dog'

output = input.split(/ (?![^[]*])/)

console.log(output)

这两个片段仅在括号未嵌套时才有效,否则您需要解析器而不是正则表达式。


以上是使用正则表达式跳过括号[]拆分字符串的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>