Regex Greedy vs Lazy Quantifiers
Greedy and lazy quantifiers are one of the most common sources of regex bugs. Understanding the difference prevents accidentally matching too much — or too little.
Greedy (default)
Greedy quantifiers (*, +, {n,m}) match as much as possible. Given the string <b>bold</b> and <i>italic</i>, the pattern <.+> matches the entire string from first < to last > — not just one tag.
- * — zero or more (greedy)
- + — one or more (greedy)
- ? — zero or one (greedy)
- {n,m} — between n and m (greedy)
Lazy (reluctant)
Add ? after any quantifier to make it lazy: *?, +?, ??, {n,m}?. Lazy quantifiers match as little as possible. The pattern <.+?> on the same string matches <b>, </b>, <i>, </i> separately.
- *? — zero or more (lazy)
- +? — one or more (lazy)
- ?? — zero or one (lazy)
- {n,m}? — between n and m (lazy)
When to use which
- HTML tag matching: use lazy (<.+?>)
- Quoted string extraction: use lazy (".*?")
- Most-specific match: use lazy
- Longest possible match: use greedy (default)
Frequently Asked Questions
Does lazy mean slow?
In terms of speed, lazy can actually be faster in some cases because it stops at the first valid match rather than backtracking from the longest. The name refers to matching behavior, not performance.
What is possessive quantifier?
Possessive quantifiers (++, *+, ?+) are like greedy but never backtrack. JavaScript does not support possessive quantifiers.
