Regex · <code>.*</code>
Greedy and lazy matching
Greedy quantifiers take as much as possible; adding ? makes them lazy and take as little as possible.
Key facts
| Greedy | <code>.*</code> |
|---|---|
| Lazy | <code>.*?</code>, <code>+?</code>, <code>??</code>, <code>{n,m}?</code> |
| Possessive | <code>.*+</code> in PCRE and Java, not JavaScript |
| Default | Every quantifier is greedy |
| Effect | Greedy backtracks from the right; lazy expands from the left |
| JavaScript | Supports lazy quantifiers; no possessive quantifiers |
| PCRE / Java | Support possessive quantifiers and atomic groups |
| Typical use | <code><.+?></code> to stop at the first closing bracket |
The same pattern, two answers
Against the text <b>one</b><i>two</i>, the pattern <.+> matches the whole string because .+ consumes everything and then backtracks only as far as needed. <.+?> stops at the first >, returning <b>.
Lazy is not “correct” by default: it is slower when the match is near the end, and a lazy quantifier followed by a pattern that never matches still scans the entire input. Choose based on which delimiter should bound the match.
Possessive quantifiers and atomic groups
A possessive quantifier such as .*+ consumes as much as possible and never gives anything back. That prevents backtracking entirely, which can be a performance win and a correctness trap: if the rest of the pattern needed a character that was consumed, the match fails with no retry.
Atomic groups (?>...) express the same idea for a subpattern. Neither is available in JavaScript, so portable patterns rely on precise classes and anchors instead of possessive syntax.
Frequently asked questions
What does .*? mean?
A lazy repetition of any character: it matches as few characters as possible while letting the rest of the pattern succeed.
Why is my .* match too long?
The quantifier is greedy. Add ? to make it lazy or replace the dot with a class that excludes the delimiter.
Can JavaScript use possessive quantifiers?
No. ECMAScript supports lazy quantifiers but not possessive quantifiers or atomic groups.