Greedy, Lazy and Backtracking
See how the regex engine backtracks, choose between greedy, lazy and negated-class patterns, and recognize patterns that cause catastrophic slowdowns.
Welcome back!
Step 1 of 14Learn
How the engine backtracks
Most regex engines in programming languages, including those in JavaScript, Python, Java, PCRE and .NET, are backtracking engines. To understand performance and some surprising results, you need to see how they think.
Match a.*c against "abcbc":
amatches "a.".*is greedy and swallows everything: "bcbc." Now the engine is at the end.cneeds a "c," but there's nothing left. The engine backtracks:.*gives back one character, "c," andctries again. Success.
Result: "abcbc," the longest possible match.
Each time a quantifier or alternation could have made a different choice, the engine leaves a backtracking point, like a breadcrumb at a fork in a trail. When something later fails, it returns to the most recent fork and tries the next option. For simple patterns this costs nothing noticeable. But the number of forks can multiply, and that's where trouble starts.
Lazy quantifiers reverse the order of choices: a.*?c first tries to match zero characters with .*?, then one, and so on, stopping at the first "c." The result is "abc." Same engine, same backtracking, different preference.
Step 2 of 14Practice · Work it out
Applied to the text "<a><b>", how many characters long is the match of the greedy pattern <.*>?
Step 3 of 14Practice · Diagram
Backtracking, frame by frame: <.+?> vs <.+>
Both patterns run on "<a><b>". The lazy one tries to stop early; the greedy one tries to run long.
Which frame shows the engine undoing earlier work?
Tap the shape that answers the question, then press Check.
- Lazy: take 1 char (a)
- Lazy: > fits next? Yes
Match "<a>". Done after very few steps.
- Greedy: take all (a><b>)
- Greedy: give back one
The final > is released and matched: "<a><b>".
Step 4 of 14Learn
Three ways to match "up to the next X"
A very common task is matching from one delimiter to the next: a quoted string, an HTML tag, a value up to a comma. You have three tools, and they behave differently.
Text: name="Ana", city="Lyon"
- Greedy dot:
".*"matches"Ana", city="Lyon", from the first quote to the last one. Almost never what you want. - Lazy dot:
".*?"matches"Ana", then"Lyon". Correct here, but the engine still tests the closing quote at every step, and lazy dots can cross lines (with thesflag) or delimiters you didn't anticipate. - Negated class:
"[^"]*"also matches"Ana"and"Lyon". The class cannot consume a quote, so the match stops at the first closing quote with no backtracking at all.
The negated class is usually the best choice: it states the rule precisely ("anything except the delimiter"), it's efficient, and it behaves the same in every flavor. To match CSV-like fields up to a comma, use [^,]*; to match a tag, <[^>]+>; to match a line's content, [^\n]*.
Lazy quantifiers remain useful when the closing delimiter is more than one character, such as HTML comments: <!--.*?-->, where a single negated class can't express "anything except the sequence -->."
Step 5 of 14Practice · Choose one
Which pattern most reliably matches each single-quoted string in say 'hi' and 'bye', without backtracking?
Step 6 of 14Learn
Catastrophic backtracking
Some patterns create so many backtracking points that the engine effectively tries an exponential number of combinations. This is catastrophic backtracking, and it can freeze a program for seconds, minutes or longer on a short input.
The classic culprit is a nested quantifier, such as (a+)+$. Apply it to "aaaaaaaaaaaaaaaaaaaaaaaa!" (24 a's and an exclamation mark). The match must fail because of the "!", but before giving up, the engine tries every way to split the a's between the inner and outer +: one group of 24, two groups of 12 and 12, three groups of various sizes, and so on. For n characters there are about 2^(n−1) ways. At 24 a's, that's more than 8 million attempts; at 40, over 500 billion.
Similar traps:
(\w+\s?)+$: words and optional spaces can be split in many ways.(a|a)*or(a|ab)*: overlapping alternatives.(.*,)*: a dot that can also match the delimiter.
The common thread: the same text can be matched by the pattern in many different ways, and a failure at the end forces the engine to try them all. Successful matches are often fast; it's the near-misses, inputs that almost match, that explode.
Step 7 of 14Try the calculator
How bad is a nested quantifier?
For a pattern like (a+)+$ failing on n repeated characters, a backtracking engine may try about 2^(n−1) splits. Assume the engine manages 100 million attempts per second.
- Attempts, about 2^(n−1)
- 16,777,216
- Seconds to fail
- 0.168
- Days to fail
- 0
Step 8 of 14Practice · Work it out
A backtracking engine tries about 2^(n−1) combinations when the pattern (a+)+$ fails on n letter a's. Each extra character multiplies the work by what factor?
Step 9 of 14Learn
Defending against ReDoS
When a vulnerable pattern processes input from users, an attacker can send a crafted string that ties up the server's CPU. This is a regular expression denial of service (ReDoS), and it has caused real outages at well-known companies. Defenses:
- Avoid nested quantifiers over the same characters.
(a+)+is equivalent toa+;(\w+\s?)+can usually become\w+(\s\w+)*, where each piece of text can be matched only one way. - Make alternatives mutually exclusive, so at most one can match at any position.
- Prefer negated classes to dots:
"[^"]*"instead of".*". - Limit input length before matching. A 50-character limit on a name field shrinks the worst case dramatically.
- Use possessive quantifiers or atomic groups where supported (
a++,(?>...)in PCRE, Java and recent Python versions). They never give back characters, so they create no backtracking points. - Use a linear-time engine for untrusted patterns or input. Engines such as RE2 (used by Go and available as libraries for other languages) and Rust's regex crate guarantee time proportional to input length, at the cost of features such as backreferences and, in most of them, lookarounds.
- Set timeouts where the platform allows, as .NET does.
Linters and static analysis tools can also flag risky patterns before they reach production.
Step 10 of 14Note
Step 11 of 14Practice · Code challenge
Write quoted(text) that returns an array of the contents of every double-quoted string in the text, without the quotes, in order. Use a negated character class (not a dot), with a capture group and matchAll.
quoted('name="Ana", city="Lyon"')quoted('say "" then "x y z"')quoted("no quotes here")
Step 12 of 14Tap to reveal
Why some engines never backtrack
Backtracking engines
JavaScript, Python, Java, PCRE and .NET try alternatives one by one and back up on failure. This supports powerful features like backreferences and lookarounds but allows exponential worst cases.
Automaton-based engines
Tools such as RE2, Go's regexp package, Rust's regex crate and classic grep simulate all possible paths at once, like a machine moving through states. Their running time grows in proportion to the input length.
The trade-off
Linear-time engines give up backreferences and, in most implementations, lookarounds, because those features cannot be expressed as a simple state machine.
Practical choice
For patterns you write and test yourself, a backtracking engine with careful patterns is fine. For patterns or input from untrusted users, a linear-time engine removes the ReDoS risk entirely.
Step 13 of 14Practice · Select all that apply
Which of these patterns are at risk of catastrophic backtracking on long inputs that fail to match? Select all that apply.
Select all that apply.
Step 14 of 14Practice · What would you do?
What would you do?
A web app validates a "full name" field with ^([A-Za-z]+\s?)+$. Monitoring shows the server occasionally freezing for seconds on sign-up requests with long, odd names. What is the best fix?
Lesson complete!