What is the difference between:
(.+?)
and
(.*?)
when I use it in my php preg_match
regex?
* means zero-or-more, and + means one-or-more. So the difference is that the empty string would match the second expression but not the first.
The asterisk is known as a repeater symbol, meaning the preceding character can be found 0 or more times. For example, the regular expression ca*t will match the strings ct, cat, caat, caaat, etc.
*? is non-greedy. * will match nothing, but then will try to match extra characters until it matches 1 , eventually matching 101 . All quantifiers have a non-greedy mode: .
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
The first (+
) is one or more characters. The second (*
) is zero or more characters. Both are non-greedy (?
) and match anything (.
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With