【问题标题】:JavaScript doesn't split string correctlyJavaScript 不能正确分割字符串
【发布时间】:2020-02-14 02:09:48
【问题描述】:

根据ECMA-262 §21.1.3.19 String.prototype.split

String.prototype.split ( separator, limit )

返回一个 Array 对象,其中存储了将此对象转换为 String 的结果的子字符串。通过从左到右搜索分隔符的出现来确定子字符串; 这些出现不是返回数组中任何子字符串的一部分,而是用于分割字符串值

但是,我目前正在观察一种奇怪的行为。代码如下:

let s = new String("All the world's a stage, And all the men and women merely players;");
console.log(s.split(/( |o)men /));

预期输出:

[
  "All the world's a stage, And all the",
  'and w',
  'merely players;'
]

实际输出:

[
  "All the world's a stage, And all the",
  ' ',
  'and w',
  'o',
  'merely players;'
]

这里发生了什么?我该怎么写才能匹配“men”或“omen”?


环境:

~ $ node --version
v13.8.0

仅供参考:

Python3 的行为相同。

import re
s = "All the world's a stage, And all the men and women merely players;"
print(re.compile("( |o)men ").split(s))
  #=> ["All the world's a stage, And all the", ' ', 'and w', 'o', 'merely players;']
print(re.compile("(?: |o)men ").split(s))
  #=> ["All the world's a stage, And all the", 'and w', 'merely players;']

这种奇怪的(至少对我而言)行为可能有合理的理由或实际用例......

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    String.prototype.split spec 还说(在同一段中):

    separator 的值可以是任意长度的字符串,也可以是具有@@split 方法的对象,例如 RegExp。

    如果我们查看 RegExp.prototype [ @@split ] 的规范,它会说:

    如果正则表达式包含捕获括号,则每次匹配分隔符时,将捕获括号的结果(包括任何未定义的结果)拼接到输出数组中。

    这解释了您所看到的行为。要解决它,只需使用非捕获组,即

    let s = new String("All the world's a stage, And all the men and women merely players;");
    console.log(s.split(/(?: |o)men /));

    或者,for better performance,因为你只是交替单个字符,所以使用字符类:

    let s = new String("All the world's a stage, And all the men and women merely players;");
    console.log(s.split(/[ o]men /));

    【讨论】:

      【解决方案2】:

      String.prototype.split()

      找到后,从字符串中删除分隔符,并以数组的形式返回子字符串。

      如果separator是带捕获括号的正则表达式,那么每次separator匹配时,捕获括号的结果(包括任何未定义的结果)都会拼接到输出数组中。

      【讨论】:

        猜你喜欢
        • 2012-02-04
        • 2013-07-20
        • 2014-10-05
        • 1970-01-01
        • 2014-12-13
        • 1970-01-01
        • 1970-01-01
        • 2020-05-23
        相关资源
        最近更新 更多