Hone

Lessons · Regex · *?: stopping at the first match

As little as possible

A ? after a quantifier makes it lazy: .*? and +? take as few characters as will still let the rest of the pattern match, instead of as many.

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

<b>one</b> and <b>two</b> matched with <b>.*</b> gives the whole line, because .* grabs everything to the last </b>. Lazy stops at the first.

How to think about it

When a greedy quantifier swallows past the boundary you wanted, make it lazy, or better, replace . with a class that cannot cross the boundary: [^<]* stops at the next tag by construction.

Worked example

pattern: <b>.*</b>
Greedy: as much as possible.
text: <b>one</b> and <b>two</b>
One match: the whole thing, from the first <b> to the last </b>.
pattern: <b>.*?</b>
Lazy: as little as possible.
text: <b>one</b> and <b>two</b>
Two matches: <b>one</b> and <b>two</b>.
pattern: a+?
At least one, then stop.
text: aaa
Matches a single a.

Your turn

The text inside the first pair of quotes.

"(.)"

The trap

Lazy is not 'shortest overall': it still starts at the earliest position and extends one step at a time. A negated class like [^"]* is often clearer and faster.

Practise *?: stopping at the first match on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.