Greedy vs. lazy quantifiers
Phase 3's quantifiers (+, {n,m}) are all greedy by default - they
grab as much text as possible while still letting the whole pattern match.
Usually that's what you want, but it has a classic failure mode: pull the
text between the first pair of quotes in 'Say "hello" and "goodbye"' and a
greedy .+ doesn't stop at the first closing quote - it stops at the
last one, because .+ between the outer quotes can still match, greedily,
all the way to the end.
Add a ? right after the quantifier and it becomes lazy : it grabs as
little as possible instead, stopping the moment the rest of the pattern is
satisfied. .+? between two quotes stops at the very first closing quote.
Same pattern shape, opposite instinct - and knowing which one you need is the
difference between "it works" and "it somehow grabbed the whole file."
Your task: write extractGreedy(str), returning the text between the
first " and the last " in str using a greedy quantifier, and
extractLazy(str), returning the text between the first " and the next
" using a lazy quantifier. Return null if str has no quoted text.
You'll practice:
Seeing greedy .+ overshoot to the last possible match
Making a quantifier lazy with .+? to stop at the first match instead
Show a hint
Show solution
Related reading: Using Regex for Real (and the Gotchas) →
Previous Next