C.W.K.
Stream
Lesson 08 of 12 · published

Greedy vs Lazy — When It Matters

~8 min · greedy, lazy, decision

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

It only matters when the rest of the pattern is also flexible

Greedy and lazy produce the same result when the rest of the pattern is unambiguous. \d+abc and \d+?abc both match the same way against 1234abc — there's only one possible match.

The difference shows up when the pattern boundary is fuzzy: when the next thing the engine looks for can appear in multiple places. Then greedy goes to the last possible spot, lazy stops at the first.

Three rules of thumb

1. Extracting between markers? Use lazy or negated class. Tags, quoted strings, comments, anything bracketed. The first closing marker is what you want.

2. Validating fixed-shape input? Greedy is fine, often better. Phone numbers, dates, IDs — there's only one way to match them. Greedy backtracks slightly less in the success case.

3. Searching for one occurrence in noisy text? Greedy default. Logs, free-form documents. You usually want "as much as fits the pattern" because that's likely the real value.

The 'I just don't know' default

If you can't decide, write the pattern greedy first, then check what it matches on real input. If it eats too much, switch to lazy or negated class. Don't preemptively reach for lazy because "it sounds safer" — sometimes greedy is what you actually want.

Code

When the choice doesn't matter·python
import re

# Greedy and lazy produce the same result here
re.findall(r'\d+abc', '1234abc')   # ['1234abc']
re.findall(r'\d+?abc', '1234abc')  # ['1234abc']  — same

# But the moment the boundary is ambiguous, they diverge
re.findall(r'<.*>', '<a><b><c>')   # ['<a><b><c>']  greedy
re.findall(r'<.*?>', '<a><b><c>')  # ['<a>', '<b>', '<c>']  lazy

External links

Exercise

Take a multi-line HTML or Markdown document. Try extracting all [link text](url) pairs with greedy first, then lazy. Notice which one gives you what you actually want. Now switch to a negated class. Compare all three.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.