正则表达式加上星号区别? [英] Regex plus vs star difference?
问题描述
两者之间有什么区别
(.+?)
和
(.*?)
何时在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屋!