什么是正则表达式中的双加号?

2022-08-30 12:25:27

我一直在一些PHP脚本中看到这一点:

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

双加号是什么意思?


答案 1

这是一个所有格量词

这基本上意味着,如果正则表达式引擎稍后无法匹配,它将不会返回并尝试撤消在此处进行的匹配。在大多数情况下,它允许引擎更快地失效,并且可以在您需要的地方为您提供一些控制 - 这对于大多数用途来说非常罕见。


答案 2

举一个非常简单的例子:

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

  1. 正则表达式:部分匹配!\d+?.

    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. 正则表达式:完全匹配!\d+.

    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. 正则表达式:没有匹配!\d++.

    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.
    

推荐