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

Backtracking: an overview

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

What the engine does when a greedy quantifier fails, and why it can be expensive.

What you'll learn in this lesson

  • Visualize how the NFA engine tries a greedy quantifier and backtracks to failure.
  • Recognize patterns vulnerable to ReDoS (Regular expression Denial of Service), such as (a+)+b or (\w+\s*)+@.
  • Rewrite an O(2^n) explosive pattern into a linear O(N) pattern by eliminating nested quantifiers and ambiguity.
  • Replace generic .* between delimiters with explicit negated classes ([^"]*, [^<]*) to eliminate backtracking.

Overview

When a greedy quantifier consumes too much and the next token fails, the engine goes back one step at a time (backtracking) to look for a valid compromise. With single quantifiers on short texts it costs microseconds; but with nested or overlapping quantifiers on input without final match, the combinations grow exponentially O(2^n) blocking…

Sections covered in this lesson

  1. 1Mental model: linear vs explosive backtracking
  2. 2Progressive examples
  3. 3Guided laboratory
  4. 4Check for understanding
Pro Lesson · Module 2 — Quantifiers

Unlock "Backtracking: an overview" and the full Regex Course curriculum

What the engine does when a greedy quantifier fails, and why it can be expensive.

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.