Quantifiers | Description |
---|---|
? | Match the preceding character or subexpression 0 or 1 times (preferably 1). |
* | Match the preceding character or subexpression 0 or more times (as many as possible). |
+ | Match the preceding character or subexpression 1 or more times (as many as possible). |
{n} | Match the preceding character or subexpression exactly n times. |
{min,} | Match the preceding character or subexpression min or more times (as many as possible). |
{0,max} | Match the preceding character or subexpression max or fewer times (as close to max as possible). |
{min,max} | Match the preceding character or subexpression at least min times but no more than max times (as close to max as possible). |
Lazy Quantifiers | Description |
?? | Match the preceding character or subexpression 0 or 1 times (preferably 0). |
*? | Match the preceding character or subexpression 0 or more times (as few as possible). |
+? | Match the preceding character or subexpression 1 or more times (as few as possible). |
{n}? | Match the preceding character or subexpression exactly n times. No difference between greedy and lazy version. |
{min,}? | Match the preceding character or subexpression min or more times (as close to min as possible). |
{0,max}? | Match the preceding character or subexpression max or fewer times (as few as possible). |
{min,max}? | Match the preceding character or subexpression at least min times but no more than max times (as close to min as possible). |
A greedy quantifier always attempts to repeat the sub-pattern as many times as possible before exploring shorter matches by backtracking.
Generally, a greedy pattern will match the longest possible string.
By default, all quantifiers are greedy.
A lazy (also called non-greedy or reluctant) quantifier always attempts to repeat the sub-pattern as few times as possible, before exploring longer matches by expansion.
Generally, a lazy pattern will match the shortest possible string.
To make quantifiers lazy, just append ?
to the existing quantifier, e.g. +?
, {0,5}?
.
The notion of greedy/lazy quantifier only exists in backtracking regex engines. In non-backtracking regex engines or POSIX-compliant regex engines, quantifiers only specify the upper bound and lower bound of the repetition, without specifying how to find the match -- those engines will always match the left-most longest string regardless.