正则表达式加上星号区别? [英] Regex plus vs star difference?

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

问题描述

两者之间有什么区别

(.+?)

(.*?)

何时在php preg_match正则表达式中使用它?

解决方案

它们被称为量词.

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

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

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

修饰符后的?会更改其行为以使该修饰符不舒适",这意味着它将尽可能少地匹配.

贪婪/贪婪示例

例如,字符串" abab "

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

a.*?b仅匹配开头的"ab"(preg_match_all将返回两个匹配"ab")

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

What is the difference between:

(.+?)

and

(.*?)

when I use it in my php preg_match regex?

解决方案

They are called quantifiers.

* 0 or more of the preceding expression

+ 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.

Example greedy/ungreedy

For example on the string "abab"

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

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

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

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

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