Skip to main content
Module 2 · Lesson 3 of 47/32 in the course~16 min
Module lessons (3/4)

Greedy vs lazy

Lesson preview5 hands-on exercises readyRegex Course · Module 2 — Quantifiers

By default quantifiers are greedy (.*); add ? for the lazy version (.*?).

What you'll learn in this lesson

  • Operationally distinguish greedy behavior (greedy: consumes the maximum) from lazy behavior (lazy: consumes the minimum).
  • Apply ? after any quantifier (*?, +?, ??, {n,m}?) to extract multiple delimiters without merging them together.
  • Recognize when a denied class ([^"]*, [^>]*) is preferable to even .*? for performance and clarity.
  • Mentally draw the engine checkpoint on HTML tags, quoted strings, and square brackets.

Overview

By default each quantifier is greedy (greedy): it consumes all possible text, even crossing intermediate markers, moving back only the minimum necessary to pass the next token. Adding ? after a quantifier (*?, +?, ??, {n,m}?) gives you lazy mode, which tries the smallest possible expansion first.

Sections covered in this lesson

  1. 1Mental model: greedy vs lazy vs negated class
  2. 2Progressive examples
  3. 3Guided laboratory
  4. 4Check for understanding
Pro Lesson · Module 2 — Quantifiers

Unlock "Greedy vs lazy" and the full Regex Course curriculum

By default quantifiers are greedy (`.*`); add `?` for the lazy version (`.*?`).

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Regex Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.