Lessons · Regex · greedy vs lazy
Greedy takes all it can
* and + match as much as possible; adding ? (.*?) makes them stop at the first chance.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Extracting the first quoted string or the first tag from a line with several.
How to think about it
Where should the match stop? If your match runs past where you meant it to stop, make the quantifier lazy, or use a negated class like [^"]* that cannot cross the delimiter.
Worked example
pattern: "(.*)"Greedy.
text: say "hi" and "bye"Captures: hi" and "bye. Too much.
pattern: "(.*?)"Lazy: captures hi.
pattern: "([^"]*)"Same result, and faster: cannot cross a quote.
Your turn
First bold tag only.
<b>.*</b>
Test a pattern against real text
The trap
Lazy is not 'shortest overall'; it is 'shortest from where it started'. Combined with anchors it can still surprise.
Practise greedy vs lazy on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.