【问题标题】:What is double plus in regular expressions?什么是正则表达式中的双加?
【发布时间】:2011-05-28 05:38:38
【问题描述】:

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

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

双加是什么意思?

【问题讨论】:

标签: php regex


【解决方案1】:

那是Possessive Quantifier

这基本上意味着如果正则表达式引擎稍后匹配失败,它不会返回并尝试撤消它在这里所做的匹配。在大多数情况下,它允许引擎fail much faster,并且可以让您在需要的地方进行一些控制——这对于大多数用途来说是非常罕见的。

【讨论】:

  • 只是为了澄清这一点:它可以撤消整个组,但没有组内。我不确定这是否足够清楚,但链接解释得很好。
  • 你能提供例子暴露++和+的区别吗?
【解决方案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.
    

【讨论】:

  • 我希望我早在几年前就知道你的解释很棒。谢谢。
  • 很好的解释亲爱的安德烈。我不知道+ 可以像*? 一样变得懒惰。
猜你喜欢
  • 2011-06-15
  • 2015-06-09
  • 2013-04-07
相关资源
最近更新 更多