简体   繁体   English

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

[英]What is double plus in regular expressions?

I have been seeing this in some PHP script: 我在一些PHP脚本中看到过这个:

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

What does the double plus mean? 双加是什么意思?

That's a Possessive Quantifier . 这是一个占有量词

It basically means that if the regex engine fails matching later, it will not go back and try to undo the matches it made here. 它基本上意味着如果正则表达式引擎稍后失败匹配,它将不会返回并尝试撤消它在此处所做的匹配。 In most cases, it allows the engine to fail much faster , and can give you some control where you need it - which is very rare for most uses. 在大多数情况下,它允许引擎更快发生故障 ,并且可以在您需要的地方为您提供一些控制 - 这在大多数情况下非常罕见。

To give you a very simple example: 给你一个非常简单的例子:

Let's say you have a string "123" . 假设你有一个字符串"123" The matched characters have a ^ underneath in the following examples. 在以下示例中,匹配的字符具有下面的^

  1. Regex: \\d+?. 正则表达式: \\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+. 正则表达式: \\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++. 正则表达式: \\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. 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM