javascript - `+` 和 `*` 运算符的贪婪行为

标签 javascript regex regex-greedy

<分区>

我有一个变量,

var inp = "B123213";

现在当我应用下面的正则表达式时,

var rg = /\d+/;

并执行String匹配操作,

console.log(inp.match(rg));

我得到的输出为 123213,表示表达式是贪心的。但是当我使用 * 而不是 + 时,表达式不会返回匹配项。请帮助我理解为什么返回空匹配项。它不应该返回相同的结果吗。

由于文档中提到了 ?

If used immediately after any of the quantifiers *, +, ?, or {}, makes the quantifier non-greedy (matching the fewest possible characters), as opposed to the default, which is greedy (matching as many characters as possible). For example, applying /\d+/ to "123abc" matches "123". But applying /\d+?/ to that same string matches only the "1".

我希望仅在应用 /\d*?/ 时出现空匹配。

最佳答案

将您的字符串更改为 123213,它将匹配所有数字。

除非必须,否则引擎不会前进。

在这里它看到一个 B123213 并且它可以匹配 nothing\d* 在那个位置,
确实如此。

所以,首先是位置,其次是量词。

关于javascript - `+` 和 `*` 运算符的贪婪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26638220/

相关文章:

python - 在环视中引用命名组 (Python 2.x)

javascript - 什么时候开始使用 VueX 商店?

javascript - 通过一次表单提交将多个文件上传到一个文件夹中

javascript - Photoslide javascript 在 Firefox 中有效,但在 IE 中无效

c# - 替换所有出现和正则表达式

php - 非贪婪正则表达式

javascript - 将不透明度更改切换为复选框图像

Javascript 对捕获的正则表达式执行算术运算

python - 相同的模式但不同的结果

regex - 需要正则表达式来查找两个标记之间的子字符串