正则表达式中的“double plus”是什么?

41

我在一些PHP脚本中看到了这个:

[a-zA-Z0-9_]++

双加号代表什么意思?


16
当然是双倍好的。:o) - deceze
2
此问题已添加到Stack Overflow 正则表达式 FAQ中,位于“量词”一节下。 - aliteralmind
2个回答

44

这是一个所有格量词

基本上意味着如果正则表达式引擎在后续匹配失败,它不会回溯并尝试撤消先前的匹配。在大多数情况下,它可以让引擎更快地失败,并且可以使您在需要时掌握一些控制 - 这对于大多数用途来说非常罕见。


3
为了澄清一下:它可以撤销整个组,但不能撤销组内的任何内容。我不确定这是否已经表述清楚,但链接中很好地解释了这一点。 - Kobi
3
你能举例说明 ++ 和 + 的区别吗? - gstackoverflow

41

举个非常简单的例子:

假设你有一个字符串"123"。在下面的示例中,匹配的字符下方都有一个^

  1. Regex: \d+?. partial match!

    123  # The \d+? eats only 1 because he's lazy (on a diet) and leaves the 2 to the .(dot).
    ^^   # This means \d+? eats as little as possible.
    
  2. Regex: \d+. full match!

    123  # The \d+ eats 12 and leaves the 3 to the .(dot).
    ^^^  # This means \d+ is greedy but can still share some of his potential food to his neighbour friends.
    
  3. Regex: \d++. no match!

    123  # The \d++ eats 123. He would even eat more if there were more numbers following. 
         # This means \d++ is possessive. There is nothing left over for the .(dot), so the pattern can't be matched.
    

我希望多年前就知道这个。你的解释很好,谢谢。 - WORMSS
1
很好的解释,亲爱的安德烈。我不知道 + 可以像 * 一样用 ? 变成懒惰模式。 - Anoushiravan R

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接