Greedy and lazy quantifiers

Intermediate · 13 min

Quantifiers grab as much as they can, then give back. Compare ".*", ".*?" and "[^"]*" on one line, and see where lazy matching still goes wrong.

Before thisNegated classesQuantifiers: star, plus and questionCounted repetition

RobertElderSoftware · 19 min

Greedy and lazy quantifiers

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by RobertElderSoftwareReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Quantifiers are greedy by default: * + ? and {n,m} take as many characters as they can, then give characters back one at a time until the rest of the pattern fits.
  • Adding ? makes a quantifier lazy: *? +? ?? {n,m}? take as few as possible and extend one character at a time. On the line say "hi" and "bye", ".*" matches both quotes' span and ".*?" matches "hi".
  • Lazy does not mean shortest overall. The match still starts at the leftmost possible position, and the engine will extend a lazy part as far as needed.
  • A negated class such as "[^"]*" is usually better than either: it cannot cross the closing quote, so it needs no give-back, and it makes the intent explicit.
  • Lazy quantifiers are a backtracking-engine feature. macOS grep -E accepted ".*?" but macOS sed -E rejected it with 'repetition-operator operand invalid'.

The pattern that ate the line

Here is a line with two quoted words and a pattern that looks like it should find the first one:

const s = `say "hi" and "bye" now`;
s.match(/".*"/)[0]      // "hi" and "bye"

You wanted "hi". You got everything from the first quote to the last quote on the line. That’s not a bug in the engine. .* is greedy: it takes as many characters as it possibly can. Greediness is the default for every quantifier in the previous two lessons.

Take everything, then give back

The mechanism is worth seeing, because it explains the surprise. When the engine reaches .*, it first claims the whole rest of the line. Then it tries to match the next piece of the pattern, the closing ". At the end of the line there is no quote. So the engine backtracks: it hands back one character at a time from the end of what .* took and tries the quote again. It stops at the first position, working backwards, where a quote fits. That is the last quote on the line.

I wrote a small model of that order of attempts, three ways, and ran it on the same line. It is my own illustration of the order, not the internals of any real engine:

".*"  greedy  ->  '"hi" and "bye"'   closing-quote checks: 6
".*?" lazy    ->  '"hi"'             closing-quote checks: 3
"[^"]*" class  ->  '"hi"'            closing-quote checks: 1
22 characters in the line

Greedy started with the whole tail and gave back five characters before it found a quote. Lazy started with nothing and took one character at a time until the next one was a quote.

Lazy: take as little as possible

Put a ? after any quantifier and it flips to lazy. It now claims the minimum and extends one character at a time, only if the rest of the pattern fails:

s.match(/".*?"/g)                 // [ '"hi"', '"bye"' ]
"aaa".match(/a+?/g)               // [ 'a', 'a', 'a' ]
"aaaaa".match(/a{2,4}?/)[0]       // "aa"      (greedy {2,4} gives "aaaa")

The forms are *?, +?, ?? and {n,m}?. The same trap shows up with markup. On <b>bold</b> and <i>it</i>, the greedy /<.+>/ swallowed the entire string, while /<.+?>/g found <b>, </b>, <i> and </i> separately.

Lazy is not “find the shortest match in the text”. The engine still tries starting positions from the left, and the lazy part will grow until the pattern succeeds:

"<a><b>x".match(/<.+?>x/)[0]      // "<a><b>x"
"aXbXb".match(/a.*?b/)[0]         // "aXb"

In the first line the lazy .+? stretched across a><b to reach the >x, because the leftmost start (the first <) is tried before any other. The match is the shortest from that start, not the shortest anywhere. And lazy still stops at line ends, since the dot does:

`"one\ntwo" "three"`.match(/".*?"/g)     // [ '" "' ]

That is a quoted value spanning two lines. The first quote can’t reach its partner across the newline, so the engine moved on and found a “match” made of the gap between two quoted values. It looks right until you read the output.

The third option: say what you mean

The negated class from an earlier lesson states the rule instead of relying on search order. "[^"]*" means a quote, any run of characters that are not quotes, a quote. The middle can’t contain a quote, so it can’t run past the next one:

s.match(/"[^"]*"/g)               // [ '"hi"', '"bye"' ]
s.replace(/".*"/, "[X]")          // say [X] now
s.replace(/".*?"/g, "[X]")        // say [X] and [X] now

In my model the class needed one check, because it stops on its own. Whether a real engine does exactly that depends on its optimisations, which I did not inspect, but the shape of the argument holds. It also handles the two-line value on purpose, as the previous lessons showed. So: use a negated class when the closing delimiter is a single character, and lazy when it is a longer sequence you can’t express as a class.

Other engines

Python, Perl and pcre2grep gave the same answers as JavaScript: greedy swallowed the span, ".*?" found "hi" and "bye" separately. The POSIX tools split. On macOS, grep -oE '".*?"' printed "hi" "bye", so it is lazy there, but sed -E 's/".*?"/X/g' failed with repetition-operator operand invalid, while s/"[^"]*"/X/g worked. Plain grep -o '".*"' was greedy. As I understand the POSIX standard, it has no lazy form, so a negated class is the portable answer. I did not run GNU tools or a strict POSIX implementation.

Lazy matching is also still backtracking. A bad lazy pattern on long input can be slow, which the catastrophic backtracking lesson measures.

About the video

The embed is a clip of RobertElderSoftware’s “Regular Expression Quantifiers: Greedy, Lazy, Possessive”, published on 18 August 2020 and 19 minutes 9 seconds long. The clip plays from the start to 12:37, which covers the chapters Quantifiers, Examples, Question Mark Star and Plus, Summary, Four Fundamental Aspects, Lazy and Backtracking. It stops before the Possessive Quantifiers chapter, which belongs to a later lesson. The description says it treats a quantifier as a minimum and maximum range, includes diagrams, and uses a regex visualiser the creator built. I couldn’t read a transcript, so I can’t confirm the explanations, and the video is more than six years old. English per its title and description.

What I did not run

GNU grep, regex101, and the creator’s visualiser. My three-way trace is a model I wrote, so don’t read the “closing-quote checks” numbers as engine step counts.

Next

After the quantifiers comes the other half of choice, picking between alternatives: Alternation.

Check yourself

  1. 01On say "hi" and "bye" now, what do ".*", ".*?" and "[^"]*" each find first?

    ".*" finds "hi" and "bye" as one span from the first quote to the last. ".*?" finds "hi", and so does "[^"]*". The last two differ in how they get there.

  2. 02Why is a lazy quantifier not the same as the shortest possible match?

    The engine still tries start positions left to right and only then expands a lazy part as needed. For <a><b>x, the pattern /<.+?>x/ matches all of <a><b>x, because the first < is the leftmost start.

  3. 03What goes wrong with /".*?"/g on a quoted value that spans two lines?

    The dot cannot cross the newline, so the first quote fails and the engine carries on. On "one\ntwo" "three" it returned only the gap between the closing quote and the next opening one.

  4. 04Why do people prefer [^"]* to .*? for quoted strings?

    It states the rule directly (anything but a quote), needs no give-back, and also handles newlines on purpose. Lazy matching only gets the right answer by testing the closing quote at every step.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark