Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex plus vs star difference? [duplicate]

Tags:

regex

php

What is the difference between:

(.+?) 

and

(.*?) 

when I use it in my php preg_match regex?

like image 871
David19801 Avatar asked Dec 20 '11 12:12

David19801


People also ask

What is difference between and * in 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.

What does Star do in regex?

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.

What is the difference between .*? and * regular expressions?

*? 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: .


2 Answers

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

like image 66
stema Avatar answered Oct 06 '22 07:10

stema


The first (+) is one or more characters. The second (*) is zero or more characters. Both are non-greedy (?) and match anything (.).

like image 31
Quentin Avatar answered Oct 06 '22 06:10

Quentin