Skip to content
uencoder

Regex Quantifiers Reference

Greedy, lazy, and possessive quantifiers and their backtracking behavior.

Quantifier Forms

Quantifiers specify how many times the preceding element may repeat. The asterisk means zero or more, the plus means one or more, and the question mark means zero or one. The curly brace form {min,max} gives explicit bounds, with either bound optional. Each quantifier has three repetition modes that differ in backtracking behavior, which affects both performance and match results on ambiguous inputs.

*
Zero or more, greedy
a* matches aaa
+
One or more, greedy
a+ matches aaa
?
Zero or one, greedy
colou?r
{n,m}
Between n and m repetitions
a{2,4}
*? +? ??
Lazy variants, match as few as possible
a+? matches one a

Greedy vs Lazy

Greedy quantifiers consume as many characters as possible, then backtrack to allow the rest of the pattern to match. Lazy quantifiers consume as few as possible, then expand if the rest of the pattern fails. The choice affects which substring is captured when multiple matches are possible. For HTML-like patterns, lazy quantifiers usually produce the intended match, while greedy ones can overshoot across tags.

Possessive Quantifiers

Possessive quantifiers, written with a trailing plus, match greedily but never give back characters through backtracking. This improves performance by preventing catastrophic backtracking on patterns that cannot match. If a possessive quantifier consumes too much, the overall match simply fails rather than trying shorter alternatives. Atomic groups provide the same no-backtrack guarantee for arbitrary subexpressions. Using possessive quantifiers is a key technique for writing safe, linear-time patterns.

Related tools

References