Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 38 ยท Character Classes and Quantifiers

Lazy Quantifiers and Backtracking Basics

Switch quantifiers to lazy mode with a trailing question mark, compare greedy and lazy matching, understand backtracking step by step, and learn when negated classes beat lazy quantifiers.

A greedy quantifier takes as much text as possible. A lazy (also called reluctant or non-greedy) quantifier does the opposite: it takes as little as possible, and extends only if the rest of the pattern fails. You make a quantifier lazy by adding a ? after it.

Greedy Lazy Meaning
* *? zero or more, as few as possible
+ +? one or more, as few as possible
? ?? zero or one, preferring zero
{n,m} {n,m}? between n and m, preferring n

A lazy quantifier does not change what can match, only which match is chosen first.

Greedy versus lazy

Node.js The classic tag example

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The lazy .+? starts with a single character and, at each step, checks whether the next token (>) matches. If it does, it stops. If not, it takes one more character and checks again.

flowchart TD
  A["'<' matches"] --> B[".+? takes one char: 'b'"]
  B --> C{"Next char is '>'?"}
  C -- "yes" --> D["Match ends: <b>"]
  C -- "no" --> E["Take one more char"]
  E --> C

A lazy quantifier grows one character at a time; a greedy one shrinks one at a time.

Lazy matters only with something after it

A lazy quantifier at the very end of a pattern matches the minimum and then stops, which is rarely what you want.

Node.js Lazy at the end

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Backtracking, step by step

Both greedy and lazy quantifiers rely on backtracking: when a later part of the pattern fails, the engine returns to an earlier choice point, changes a decision (give back a character, take one more, try the next alternative) and tries again. Every quantifier and every | is a choice point.

You can see the result of backtracking in what the groups captured. In the first example the greedy .* first swallows the whole text, then gives characters back until end can match. The second shows backtracking through alternatives.

Node.js Seeing the retreat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last example shows alternation backtracking. The engine first tries a for group 1, then c fails against b, so it tries bcd, which fits, leaving d* to match nothing. It never needed the second alternative ab of the first group.

Negated classes: the better lazy

In many cases a lazy .*? can be replaced by a negated class, which is both clearer and faster, because it never needs to backtrack through the characters it scans.

Node.js Lazy dot versus negated class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second pattern uses [^"]* for the quoted text: it says "anything except a quote" and stops by itself at the closing quote. No lazy quantifier, and no accident when the text contains a comma.

When the text you want ends at a specific character, prefer a negated class: "[^"]*" beats ".*?", and <[^>]*> beats <.*?>. Use .*? when the end marker is a multi-character sequence, like <!-- ... -->.

Multi-character end markers

A negated class works for one end character. For a longer end marker such as -->, lazy matching is the practical tool.

Node.js Lazy for multi-character endings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you make + lazy?

    Adding a question mark after any quantifier makes it lazy.
  2. 2. What does '<b>x</b>'.match(/<.+?>/)[0] return?

    The lazy quantifier stops at the first position where the next token, >, matches.
  3. 3. What is backtracking?

    Quantifiers and alternations are choice points. The engine retries them when the rest of the pattern cannot match.
  4. 4. Which is usually better for 'text up to the next quote'?

    A negated class stops at the quote by itself and avoids backtracking.

Summary

  • A trailing ? makes a quantifier lazy: it takes the least text first and grows only if needed.
  • Greedy and lazy find the same set of possible matches but choose different ones.
  • Backtracking is the engine retrying earlier choices when later parts fail.
  • Prefer negated classes like [^"]* when the end is a single character; use .*? for multi-character endings.

Next: Unicode Property Escapes