gpt4 book ai didi

javascript - 由于 "a+?"是惰性的,为什么 "a+?b"匹配 "aaab"?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:52:37 25 4
gpt4 key购买 nike

在使用 JavaScript:权威指南 学习 javascript 中的正则表达式时,我对这段话感到困惑:

But /a+?/ matches one or more occurrences of the letter a, matching as few characters as necessary. When applied to the same string, this pattern matches only the first letter a.

Now let’s use the nongreedy version: /a+?b/. This should match the letter b preceded by the fewest number of a’s possible. When applied to the same string “aaab”, you might expect it to match only one a and the last letter b. In fact, however, this pattern matches the entire string, just like the greedy version of the pattern.

为什么会这样?

这是书中的解释:

This is because regular-expression pattern matching is done by finding the first position in the string at which a match is possible. Since a match is possible starting at the first character of the string,shorter matches starting at subsequent characters are never even considered.

我不明白。谁能给我更详细的解释?

最佳答案

好的,现在您有了搜索空间“aaabc”和模式/a+?b/

/a+?b/匹配“a”吗?没有。

/a+?b/匹配“aa”吗?没有。

/a+?b/匹配“aaa”吗?没有。

/a+?b/是否匹配“aaab”?是的。

关于javascript - 由于 "a+?"是惰性的,为什么 "a+?b"匹配 "aaab"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24900026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com