php - [0-9]+ 和 [0-9]++ 有什么区别?

标签 php regex

谁能解释一下 [0-9]+[0-9]++ 有什么区别?

最佳答案

PHP 用于正则表达式的 PCRE 引擎支持 "possessive quantifiers" :

Quantifiers followed by + are "possessive". They eat as many characters as possible and don't return to match the rest of the pattern. Thus .*abc matches "aabc" but .*+abc doesn't because .*+ eats the whole string. Possessive quantifiers can be used to speed up processing.

和:

If the PCRE_UNGREEDY option is set (an option which is not available in Perl) then the quantifiers are not greedy by default, but individual ones can be made greedy by following them with a question mark. In other words, it inverts the default behaviour.

区别在于:

/[0-9]+/  - one or more digits; greediness defined by the PCRE_UNGREEDY option
/[0-9]+?/ - one or more digits, but as few as possible (non-greedy)
/[0-9]++/ - one or more digits, but as many as possible (greedy, default)

This snippet在默认贪婪模式下可视化差异。请注意,第一个代码段在功能上与最后一个代码段相同,因为附加的 +(在某种意义上)已经默认应用。

This snippet可视化应用 PCRE_UNGREEDY(默认不贪婪模式)时的差异。查看默认值是如何反转的。

关于php - [0-9]+ 和 [0-9]++ 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6186569/

相关文章:

php - 自动插入日期

regex - 如何在 Emacs 中替换单词之间的空格?

JavaScript 缩小 HTML 正则表达式

php - 性能: PHP Error Handling and Regex

PHP - 迭代两次通用迭代

php - 如何在form.serialize中获取下拉列表的值和文本?

javascript - 如何使用jQuery加载codepress

java - 在 Android 中使用正则表达式验证电话号码

C# - 用于获取文本内容的正则表达式字幕文件 (.srt)?

php - 使用正则表达式从字符串中获取变量