Skip to content

Lesson 1 of 13 · 22m

How Regex Engines Actually Match

Backtracking versus automata engines, what a choice point costs, and the mental model that lets you predict a pattern's behavior before you run it.

A regex is not a description of a string. It is a program, and the engine interpreting it decides whether that program runs in microseconds or until your health check times out. Every validator, every WAF rule, every grep one-liner executes one of two ways, and the two ways have opposite failure modes.

Two families of engines

FamilyWho uses itGuaranteeWhat it gives up
BacktrackingPerl, PCRE2, Python re, Java java.util.regex, JavaScript (V8's Irregexp), .NET, Ruby, PHPRich features: backreferences, lookarounds, lazy and possessive quantifiers, conditionalsWorst case is exponential in input length
Automata (Thompson NFA / DFA)RE2, Go regexp, Rust regex, GNU grep, mawkLinear time in input length, alwaysBackreferences and lookarounds

A backtracking engine is depth-first search over your pattern. At every choice point — a * that could take one more character, an alternation with an untried branch — it pushes a bookmark and commits to the first option. When the path fails, it pops the most recent bookmark and tries the next one. Failure is proven only when the bookmark stack is empty. An automata engine keeps every viable state alive at once and advances all of them per input character, so there is nothing to pop and nothing to retry.

Watch a backtracker think

Greedy backtracking trace

pattern:  ".*"
input:    say "hi" and "bye"

1. scan forward to the first "               -> index 4
2. .* is greedy: it eats to end of input     -> hi" and "bye"
3. need a closing " but input is exhausted   -> FAIL, backtrack one char
4. give back e, y, b ... none is a "         -> keep backing off
5. give back the final "                     -> closing " matches
result:   "hi" and "bye"      (not "hi")

Three ways to write "a quoted string," three different costs:

const line = 'say "hi" and "bye"';
console.log(line.match(/".*"/)[0]);    // "hi" and "bye"  greedy: overshoot, then give back
console.log(line.match(/".*?"/)[0]);   // "hi"            lazy: creep one char at a time
console.log(line.match(/"[^"]*"/)[0]); // "hi"            one way to match, zero retries

The third is the professional answer. It does not lean on the engine's search strategy at all: [^"]* can never consume a quote, so exactly one match is possible and the engine either finds it or fails in a single pass. Greedy and lazy are not correctness tools — they pick which of several possible matches you get first. The negated class removes the ambiguity entirely.

Leftmost is the only guarantee

Both families return the leftmost match — the one starting at the earliest input position. They disagree about which match when several start there. Backtracking engines commit to the first alternative that succeeds: /ab|abcd/ on abcd gives ab. POSIX automata return the longest: grep -oE 'ab|abcd' prints abcd. Neither is "right"; they are different specs. When you need a specific result, write the pattern so only one is possible instead of hoping the engine's policy agrees with you.

Why automata engines refuse features

A backreference like (\w+) \1 requires remembering what matched, which makes the language non-regular — matching with backreferences is NP-hard in general. RE2-family engines drop the feature rather than the guarantee. In Go, regexp.Compile("(a)\\1") returns error parsing regexp: invalid escape sequence (and regexp.MustCompile panics on it). That is not a bug; it is the bill for never hanging.

Field notes

  • Know which engine your tool uses before a pattern sees untrusted input. "It's just a regex" is how ReDoS tickets start — the catastrophic-backtracking lesson covers the outage receipts.
  • Cost scales with ambiguity: the more ways a pattern can match the same run of characters, the more paths the engine explores.
  • The expensive case is the failed match. A benchmark over inputs that match tells you nothing — test near-misses.
  • Compile once. String.matches() in Java compiles on every call, and Pattern.compile inside a loop is a classic hot spot. Python caches the 512 most recent patterns, but hoisting is still free.

Keep reading

Related articles from the SudoSecurity blog.