[0-9]+ 和 [0-9]++ 有什么区别? [英] What is the difference between [0-9]+ and [0-9]++?

查看:92
本文介绍了[0-9]+ 和 [0-9]++ 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can someone explain me what is the difference between [0-9]+ and [0-9]++?

推荐答案

PHP 用于正则表达式的 PCRE 引擎支持 "占有量词":

The PCRE engine, which PHP uses for regular expressions, supports "possessive quantifiers":

后跟+的量词是所有格".它们吃掉尽可能多的字符并且不会返回以匹配模式的其余部分.因此 .*abc 匹配 "aabc".*+abc 不匹配,因为 .*+ 吃掉了整个字符串.所有格量词可用于加快处理速度.

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.

还有:

如果设置了 PCRE_UNGREEDY 选项(一个Perl 中不可用的选项),那么默认情况下量词不是贪婪的,但可以通过在它们后面加上问号来使个别的量词变得贪婪.换句话说,它反转了默认行为.

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 visualises the difference when in greedy-by-default mode. Note that the first snippet is functionally the same as the last, because the additional + is (in a sense) already applied by default.

此代码段 将应用 PCRE_UNGREEDY(非贪婪默认模式)时的差异可视化.看看默认值是如何反转的.

This snippet visualises the difference when applying PCRE_UNGREEDY (ungreedy-by-default mode). See how the default is reversed.

这篇关于[0-9]+ 和 [0-9]++ 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆