【发布时间】: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