正则表达式加与星差? [英] Regex plus vs star difference?

查看:23
本文介绍了正则表达式加与星差?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别:

(.+?)

(.*?)

当我在我的 php preg_match 正则表达式中使用它时?

when I use it in my php preg_match regex?

推荐答案

它们被称为量词.

* 0 个或多个前面的表达式

* 0 or more of the preceding expression

+ 1 个或多个前面的表达式

+ 1 or more of the preceding expression

默认情况下,量词是贪婪的,这意味着它匹配尽可能多的字符.

Per default a quantifier is greedy, that means it matches as many characters as possible.

量词之后的 ? 改变行为使这个量词不贪婪",意味着它会尽可能少地匹配.

The ? after a quantifier changes the behaviour to make this quantifier "ungreedy", means it will match as little as possible.

贪心/不贪心的例子

例如字符串abab"

a.*b 将匹配abab"(preg_match_all 将返回一个匹配,即abab")

a.*b will match "abab" (preg_match_all will return one match, the "abab")

a.*?b 将只匹配开始的ab"(preg_match_all 将返回两个匹配,ab")

while a.*?b will match only the starting "ab" (preg_match_all will return two matches, "ab")

您可以在线测试您的正则表达式,例如在 Regexr 上,参见此处的贪婪示例

You can test your regexes online e.g. on Regexr, see the greedy example here

这篇关于正则表达式加与星差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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