How Backtracking Works in Regular Expressions
A practical guide to regex backtracking: how greedy and lazy quantifiers back up, what causes catastrophic backtracking, and how to test and fix patterns.
When a regular expression has more than one way to match, the engine has to try options and retreat when one fails. That retreat is called backtracking. It decides which part of your text a pattern matches, and it explains why some patterns that look harmless run very slowly on certain inputs. This guide shows how backtracking works with traced examples, how it affects find-and-replace results, and how to test and fix a pattern so it matches only what you intend.
What backtracking does to your text
Backtracking is a search strategy, not a text transformation. A backtracking regex engine reads the pattern from left to right and makes a choice whenever the pattern allows more than one possibility. A quantifier such as * or + (a symbol that says how many times something may repeat) creates a choice about how many characters to take, and an alternation such as cat|car creates a choice between branches. The engine saves each choice point. If a later part of the pattern fails, it returns to the most recent saved choice, tries the next option, and continues. It reports a match as soon as one full path succeeds, or reports no match after every path has been tried.
The input is your pattern plus the text being searched. The output is the position and content of the match, or no match. Backtracking never edits the text on its own, but it determines exactly which characters a match covers, so it controls what gets extracted, validated or replaced. This behavior applies to backtracking engines, which include the regex implementations commonly used in Perl, PCRE, Python, JavaScript, Java and .NET. Some engines, such as RE2 and the Rust regex crate, use a different, non-backtracking approach that avoids exponential slowdowns; they usually do not support features that need backtracking, such as backreferences.
Step by step: a greedy match that backs up
Quantifiers are greedy by default: they take as many characters as they can, then give characters back one at a time if the rest of the pattern needs them. The following illustrative trace shows the logic a backtracking engine follows. Real engines add optimizations, so the exact internal steps can differ, but the resulting match is the same.
Pattern: a.*b
Input: axxbyy
1. a matches "a"
2. .* takes "xxbyy" (everything left)
3. b fails: end of input reached
4. .* gives back one character (now "xxby"); b is tested against "y": fails
5. .* gives back another (now "xxb"); b is tested against "y": fails
6. .* gives back another (now "xx"); b is tested against "b": succeeds
Match: "axxb"
Each step where .* gives up a character is a backtrack. Note that in many engines . does not match a newline unless you enable a dot-all (sometimes called single-line) flag, so a line break in the input stops .* earlier than you might expect.
Greedy, lazy and possessive quantifiers
| Form | Example | How it behaves |
| Greedy | .* or .+ | Takes as much as possible, then gives back characters one by one |
| Lazy | .? or .+? | Takes as little as possible, then takes more one by one |
| Possessive | .+ or .++ | Takes as much as possible and never gives anything back |
| Atomic group | (?>...) | Once the group matches, the engine will not backtrack into it |
Lazy quantifiers still backtrack; they just explore choices in the opposite order. Possessive quantifiers and atomic groups remove choice points, which can make a pattern fail where a greedy version would have matched. Support for possessive quantifiers and atomic groups varies by engine and version, so check your engine's documentation before relying on them. The order of exploration changes the result when the text contains more than one candidate end point, as in this example:
Input: axxbyyb
a.*b matches axxbyyb (greedy: last possible "b")
a.*?b matches axxb (lazy: first possible "b")
a.*+b no match (possessive: .*+ keeps the final "b", so b has nothing left)
Why this matters when you replace text
In a search-and-replace, the difference between greedy and lazy matching decides how much text disappears. A classic case is trying to match a single HTML-style tag:
Input: <b>bold</b>
<.+> first match: <b>bold</b> (spans both tags and the word between)
<.+?> first match: <b>
<[^>]+> first match: <b>
Replacing matches of <.+> with an empty string would delete the word "bold" along with the tags. The lazy version and the negated character class [^>]+ (any character except >) each stop at the first closing bracket, so a global replace removes <b> and </b> separately and keeps the word. The negated class is often the better choice because it cannot run past a > at all, so the engine has less to undo.
Catastrophic backtracking
Backtracking becomes a problem when a pattern can match the same text in many different ways and the overall match eventually fails. The engine must try every combination before it can report failure. A standard illustrative example:
Pattern: ^(a+)+$
Input: aaaaaaaaaaaaaaaaaaaa!
The trailing ! means the $ anchor (end of input) can never match, so the attempt will fail. Before failing, the engine tries every way of dividing the run of a characters between the inner a+ and the outer +. A run of n letters can be split into consecutive non-empty groups in 2^(n-1) ways, so in a naive backtracking engine each additional a roughly doubles the work. Short inputs finish instantly, which is why the problem often goes unnoticed until a longer near-miss string arrives. Some engines include optimizations or limits that catch certain cases, but a pattern should not depend on them. When untrusted input can trigger this, the slowdown is known as a regular expression denial of service (ReDoS).
- Nested quantifiers over the same characters, such as (a+)+, (a*)* or (\w+)*
- Alternatives that can match the same text, such as (a|a)+ or (\d|\d\d)+
- Adjacent quantified parts that overlap, such as \d*\d* or .*.*x
- A repeated group with an optional separator, such as (\w+\s?)+, where words can be split in many ways
How to check a pattern step by step
- 1. Mark every choice point: each quantifier (*, +, ?, {m,n}) and each alternation (|).
- 2. For each choice point, ask whether the characters it can match overlap with the part that follows it or with another quantifier around it. Overlap is where multiple paths come from.
- 3. Test a string that should match, then test a near-miss: a long string that almost matches but fails at the very end, such as many valid characters followed by one invalid character.
- 4. Increase the length of the near-miss gradually and watch the time taken. Time that grows sharply with each added character points to catastrophic backtracking.
- 5. If your regex tester offers a debugger or step counter, use it to see where the engine keeps retreating.
- 6. Rewrite the pattern using the techniques below, then rerun every test.
Ways to reduce backtracking
- Remove nested quantifiers when a single quantifier expresses the same thing.
- Use negated character classes such as [^",]* instead of .* when you know the delimiter.
- Make alternatives mutually exclusive so only one branch can match at a given position.
- Add anchors (^, $) or fixed delimiters so the engine has fewer starting positions to try.
- Use a possessive quantifier or atomic group where your engine supports it and you know giving back characters can never help.
- Use a non-backtracking engine for untrusted input when you do not need backreferences or other features it omits.
- Set a match timeout where your engine or library allows one, as a safety net rather than a fix.
Risky: ^(a+)+$
Safer: ^a+$
Risky: ^(\w+\s?)+$
Safer: ^\w+(\s\w+)*\s?$
In the second pair, \w (word characters) and \s (whitespace) cannot match the same character, so each input string has only one way to be divided and the engine has little to undo. The rewrite keeps the original's acceptance of a single trailing whitespace character through the final \s?. Rewrites like this are easy to get subtly wrong, which is why the verification step matters.
Verify the result
A faster pattern is only correct if it matches the same text as before, or the text you actually intend. Build a small test set and run both the old and new patterns against it, comparing the matched spans, not just whether a match occurred. Include strings that should match, near-misses that should fail, an empty string, very long input, and text containing tabs, line breaks or repeated spaces. Write invisible characters explicitly in your notes, for example "word\tword" for a tab, because \s matches tabs and newlines as well as spaces. For replacements, preview the output on sample text and confirm that no meaningful content outside the intended matches was removed or altered.
Limits of this guide
The traces and examples above are illustrations of general backtracking behavior, not verified output from a specific engine. No benchmark measurements, step counts for particular engines, or feature lists for specific regex testers were available, so timing figures and tool comparisons are not included. Confirm flag behavior, quantifier support and timeout options in the documentation for the engine you use.