我观察到这些结果:
// Test 1:
var re = /a|ab/;
"ab".match(re); // returns ["a"] <--- Unexpected
// Test 2:
re = /ab|a/;
"ab".match(re); // returns ["ab"]
由于“最左边最长”的原则,我希望测试 1 和 2 都返回 ["ab"]。我不明白为什么正则表达式中两个备选方案的顺序会改变结果。
最佳答案
在下面找到原因:
Note that alternatives are considered left to right until a match is found. If the left alternative matches, the right alternative is ignored, even if it would have produced a “better” match. Thus, when the pattern /a|ab/ is applied to the string “ab,” it matches only the first letter.
(来源:Oreilly - Javascript Pocket Reference - 第 9 章正则表达式)
谢谢。
关于javascript - 似乎 JavaScript RegExp 没有找到 "leftmost longest",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19911576/