javascript - 似乎 JavaScript RegExp 没有找到 "leftmost longest"

标签 javascript regex

我观察到这些结果:

// 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/

相关文章:

javascript - 关于卸载 chrome 扩展的反馈

javascript - 左对齐饼图 (amCharts)

javascript - 在javascript中自定义响应排序

regex - PowerShell:-replace、regex 和 ($) 美元符号问题

regex - 如何在vim中搜索所有大写单词?

javascript - 使用 angularjs 将键分配给数组

javascript - 如何在 Express 中代理外部站点

regex - 不带尾部斜杠的 Htaccess 重定向可以正常工作,但使用它则不行

javascript - 是否可以使用javascript中的正则表达式来计算输入出生年份的年龄?

php - 检查 PHP 引荐来源网址