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

5

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

例如:

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

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

如果我使用简单的.split(' '),它会进入括号并返回不正确的结果。

另外,我尝试编写正则表达式,但失败了 :(

我的最后一个正则表达式看起来像这样.split(/(?:(?<=\[).+?(?=\])| )+/),并返回["tree", "car[", "]", "cat", "color[", "]", "dog"]

非常感谢任何帮助


/\w+(?:[.+?])?/g - bel3atar
4个回答

5

使用 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)

如果括号是嵌套的,那么这两个代码片段都不适用,你需要使用解析器而不是正则表达式。


对于第一个使用 .match() 的正则表达式,如果我们有一个包含 : 的字符串,例如 tree:test car[tesla BMW],它会返回 ["tree", "test", "car[tesla BMW]"],但是使用 .split() 则能正常工作!非常感谢! - MarkMark
@MarkMark:第一个代码片段已经修复。 - georg

3
你可以通过在空格上断开,向右断言1个或更多非空白字符(除括号外),并可选择从左边开始匹配直到右侧的闭合方括号后跟一个空格界限。
[ ](?=[^\][\s]+(?:\[[^\][]*])?(?!\S))

解释

  • [ ] 匹配一个空格(方括号仅用于清晰度)
  • (?= 正向预查
    • [^\][\s]+ 匹配1个或多个非 ][ 或空白字符的字符
    • (?:\[[^\][]*])? 可选地匹配 [...]
    • (?!\S) 一个右侧的空白边界
  • ) 关闭预查

正则表达式演示

const regex = / (?=[^\][\s]+(?:\[[^\][]*])?(?!\S))/g;
[
  "tree car[tesla BMW] cat color[yellow blue] dog",
  "tree car[tesla BMW] cat xml:cat xml:color[yellow blue] dog",
  "tree:test car[tesla BMW]",
  "tree car[tesla BMW] cat color yellow blue] dog",
  "tree car[tesla BMW] cat color[yellow blue dog"
].forEach(s => console.log(s.split(regex)));


1
这里是一个可以找到所有正则表达式选项的选项:

var input = 'tree car[tesla BMW] cat color[yellow blue] dog';
var matches = input.match(/\[.*?\]|[ ]|\b\w+\b/g);
var output = [];
var idx1 = 0;
var idx2 = 0;

do {
    if (matches[idx1] === " ") {
        ++idx1;
        continue;
    }

    do {
        output[idx2] = output[idx2] ? output[idx2] + matches[idx1] : matches[idx1];
        ++idx1;
    } while(matches[idx1] != " " && idx1 < matches.length);
    ++idx2;
} while(idx1 < matches.length);

console.log(output);

为了解释这个正则表达式,我们首先尝试匹配可能带有空格的[...]术语。接下来,我们查找空格分隔符,最后查找独立的单词。这是正则表达式:

\[.*?\]   find a [...] term
|         OR
[ ]       find a space
|         OR
\b\w+\b   find a word

这给我们以下中间数组:
["tree", " ", "car", "[tesla BMW]", " ", "cat", " ", "color", "[yellow blue]", " ", "dog"]

然后,我们迭代并将所有非空条目连接在一起放入输出数组中,使用实际的空格来指示真正的分隔应该发生在哪里。

0

如果你坚持使用正则表达式,我建议你观看this页面。 作者使用逗号分隔,但我相信你足够聪明将其更改为空格


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接