Reading — step 1 of 5
Learn
Lazy (Non-Greedy) Quantifiers
By default, regex quantifiers are greedy: they consume as much as possible, then back off only if needed for the rest of the pattern to match.
.*x on 'abxcxdx' → '.*' matches 'abxcxd', then 'x' matches the final x
Append ? to make a quantifier lazy (also called non-greedy or
reluctant): consume as little as possible, then expand only if needed.
.*?x on 'abxcxdx' → '.*?' matches 'ab', then 'x' matches the first x
The full set
| Greedy | Lazy | Meaning |
|---|---|---|
* | *? | 0 or more, fewest possible |
+ | +? | 1 or more, fewest possible |
? | ?? | 0 or 1, prefer 0 |
{n,m} | {n,m}? | n to m, fewest possible |
When lazy matters
The classic HTML-tag extraction:
The second is what you almost always want.
Quoted strings:
Implementation
In a backtracking engine, the only difference between greedy and lazy is the ORDER of attempts:
In an NFA simulator the priority is encoded in the epsilon-closure order:
for greedy *, the 'loop again' epsilon is tried before 'exit'; for lazy
*?, the 'exit' epsilon is tried first.
Lazy quantifiers do NOT change runtime complexity — both greedy and lazy NFA simulation are O(n·m). They only change WHICH match is returned when multiple are possible.
Gotcha
Lazy quantifiers do not always match the 'smallest' overall string. They match the leftmost match, with the lazy parts minimal given that left most match is fixed. Example:
If you want truly 'shortest', that's a different algorithm — not expressible in standard regex.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…