Greedy vs Lazy Matching
By default, quantifiers are greedy - they match as much as possible. Adding ? makes them lazy - matching as little as possible.
Greedy Behavior (Default)
The pattern <.+> matches from the first < to the LAST >, grabbing everything in between. That's greedy!
Lazy Behavior
Add ? after the quantifier to make it lazy:
Now <.+?> matches each tag separately - it stops at the first > it finds.
Comparison
| Greedy | Lazy | Behavior |
|---|---|---|
* | *? | Zero or more (prefer fewer) |
+ | +? | One or more (prefer fewer) |
? | ?? | Zero or one (prefer zero) |
{n,m} | {n,m}? | Range (prefer fewer) |
Exercises
Greedy Problems
Practical Example: Extract Values
Understanding the Difference
Think of it this way:
- Greedy: "Give me everything you can!"
- Lazy: "Give me the minimum required."
Greedy a.*b matches aXXXbYYYbZZZb (all the way to the last 'b').
Lazy a.*?b matches just aXXXb (stops at the first 'b').
When to Use Each
Use Greedy when:
- You want to match as much as possible
- There's only one possible ending point
Use Lazy when:
- You have repeating patterns
- You want the shortest match
- Parsing structured data (HTML, JSON, etc.)
Alternative: Negated Sets
Often, a negated character set is cleaner than lazy matching:
Practice Playground
Compare:
<.*>vs<.*?>".*"vs".*?"\(.*\)vs\(.*?\)
Key Takeaways
- Greedy quantifiers (
*,+,?) match as much as possible - Add
?to make them lazy:*?,+?,?? - Lazy quantifiers match as little as possible
- Negated sets
[^x]*often work better than lazy matching - Use lazy matching when parsing repeated patterns

