【问题标题】:Difference between .split(/^|\s+/) and .split(/s+/).split(/^|\s+/) 和 .split(/s+/) 的区别
【发布时间】:2019-02-12 02:08:58
【问题描述】:

我正在阅读d3 的源代码,在this lines 他们尝试按单词拆分事件名称。但是为什么他们在中使用^| 这个^|\s+ 正则表达式?当string.trim().split(/^|\s+/)string.trim().split(/\s+/) 给出不同的结果?

【问题讨论】:

  • 好吧,^|\s+\s+ 不同,因为 \s+ 匹配 1 个或多个空格,^|\s+ 匹配字符串开头 一个或多个空格.与所有其他类似“gimme-regex-explanation”请求相同。所有这些都可以在regex101.com 轻松测试。并查看那里的解释。
  • @WiktorStribiżew,你能给出使用^|\s+ 而不是\s+的首选示例吗?
  • @WiktorStribiżew,解决了这个问题

标签: javascript regex d3.js


【解决方案1】:

如果字符串不以空格开头,split 的行为没有区别:

console.log("a b c".split(/\s+/))
// => ["a", "b", "c"]
console.log("a b c".split(/^|\s+/))
// => ["a", "b", "c"]

如果开头有空格,则输出不同:

console.log(" a b c".split(/^|\s+/))
// => [" a", "b", "c"]
console.log(" a b c".split(/\s+/))
// => ["", "a", "b", "c"]

原因是匹配一个空字符串会导致 JS 正则表达式引擎跳过下一个字符。它在this answer of mine 中有描述。因此,将第一个空格包含到第一个数组项中可能被认为是一种“技巧”。

【讨论】:

  • 但前面有一个修剪 string.trim().split(/^|\s+/)。我想.trim() 可能会在以后添加
  • @Slai 所以,那段代码没有区别。 split 与这两种模式的区别是 OP 在标题中询问的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 2013-08-05
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多