How a backtracking engine matches

Intermediate · 29 min

Watch a real regex engine try start positions, take as much as it can, back off one step at a time, and pick the first alternative that works.

Before thisGreedy and lazy quantifiersAlternationHow a pattern is read: precedence and grouping

Low Byte Productions · 29 min

How a backtracking engine matches

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Low Byte ProductionsReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A backtracking engine tries to match at each start position in turn, left to right, and stops at the first position that works.
  • At each choice point it takes the preferred option first (greedy takes more, lazy takes less, alternation takes the leftmost branch) and remembers the others to return to.
  • When a later step fails, the engine backs up to the most recent choice that has an untried option and tries it. Greedy .* backs off one character at a time.
  • Order matters: /cat|category/ matches cat in JavaScript, Python, Perl and PCRE, while POSIX engines such as BSD grep -E and sed -E pick the longest, category.
  • The cost of a match is the number of steps. On my test string ".*" took 9 steps, ".*?" 6, and "[^"]*" 4. The first also swallowed too much.

What the engine is actually doing

A pattern like a.*b reads like a description: an a, then anything, then a b. But a description can’t be run. The machine underneath needs a procedure, and it has to handle choice. Does .* take two characters or five? Which branch of a|b first? The engine can’t know in advance, so it guesses, and when a guess leads to a dead end it undoes the guess and tries another.

Think of a maze with no map. You walk down the first corridor, and at every fork you remember where you were. At a dead end you go back to the last fork that still has an untried corridor. That is a backtracking engine. JavaScript, Python, Perl, Ruby and PCRE all behaved this way in my runs, and Java and .NET are described the same way, though I did not test those two.

The shape of the loop

Three rules cover most of it.

  1. Start positions. The engine tries to match the whole pattern beginning at index 0. If that fails, it tries index 1, then 2, and so on. The first index where the pattern succeeds wins.
  2. Preferred option first. Greedy quantifiers take as much as they can. Lazy ones take as little. Alternation tries the left branch first.
  3. Backtrack on failure. If a later part fails, return to the most recent choice with an unused option, and continue from there.

A trace you can read

JavaScript does not expose a step trace, so I used PCRE2 (pcre2test, version 10.49), which lets you plant a callout (?C1) that prints the position each time it is reached. Here is a.*b on axxbxx:

/a(?C1).*(?C2)b(?C3)/
    axxbxx
--->axxbxx
  1 ^^         .*
  2 ^     ^    b
  2 ^    ^     b
  2 ^   ^      b
  2 ^  ^       b
  3 ^   ^      End of pattern
 0: axxb

The first ^ is where this attempt started and the second is where the engine is. After a, the .* runs to the end of the string, because greedy takes everything. At that position (6) b fails. The engine gives one character back, so .* now covers xxbx, and b is tried at 5 and fails. Back again to 4, fail. At 3 there is a b, and the match is axxb. Three backtracks, four attempts at b, one match.

Now the start-position rule. This is \d+x on ab12y3x:

/\d+(?C1)x(?C2)/
    ab12y3x
  1   ^ ^       x
  1    ^^       x
  1      ^^     x
  2      ^ ^    End of pattern
 0: 3x

The engine skipped a and b (PCRE appears to notice that a match must begin with a digit). From the 1 it took 12, then y was not an x. It backed off to 1 alone, and 2 was not an x either. That whole start failed, so it moved to the 2, then to the 3, where \d+x finally matched 3x. JavaScript agrees on the result: /\d+x/.exec("ab12y3x") gave 3x at index 5.

Counting steps

auto_callout in pcre2test plants a callout before every pattern item, so counting lines counts steps. On "ab" and "cd" end I got:

".*"       9 steps   matches "ab" and "cd"
".*?"      6 steps   matches "ab"
"[^"]*"    4 steps   matches "ab"

JavaScript returned the same matches. The greedy .* ran to the end of the line and backed off six times to find the last quote, which is why it swallowed "ab" and "cd". The lazy version stepped forward and re-tested after each character. The negated class never needed to back off at all, because [^"] cannot cross a closing quote. The lazy dot and the negated class find the same string, and the class gets there in fewer steps. That is the measured case for [^"]*.

These counts are PCRE2’s, on a small string, and engines optimise differently. What they show is the structure: more choice points means more steps.

Order is part of the meaning

Alternation is ordered. I ran cat|category against category:

JavaScript   cat
Python 3.9   cat
Perl 5.34    cat
pcre2grep    cat
Ruby 2.6     cat
grep -oE     category     (macOS BSD grep)
sed -E       X            (the whole word replaced)

The first branch cat lets the pattern succeed, so a backtracking engine stops there. POSIX specifies leftmost-longest instead, and BSD grep -E and sed -E follow that, so they took category. Reverse the order in JavaScript and you get category. The practical rule: in a backtracking flavour, put the longer alternative first, and never assume the longest wins.

About the video

“How Do Regular Expressions Really Work?” by Low Byte Productions was published 20 October 2020 and runs 29 minutes 10 seconds. The description says it builds a basic regex engine from scratch, first naively and then with backtracking, and the chapters run Constraints, Parsing, Writing the regex engine, Testing, “Fundamental flaw” and “Implementing backtracking”. That is the same idea as the trace above, from the inside. I couldn’t read a transcript. The repository linked in the description sits under a LowLevelJavaScript account, so the code is presumably JavaScript, but I did not check. A toy engine does not show V8’s optimisations, and there is no regex101 debugger here. English per its title and description.

What I did not run

The regex101 debugger and any V8 internals. The step counts are from PCRE2 only. I did not trace lastIndex or sticky matching, and I did not look at JIT-compiled behaviour.

Next

The same machinery that makes .* back off can also back off billions of times. Catastrophic backtracking and ReDoS measures it.

Check yourself

  1. 01In /a.*b/ on 'axxbxx', why does the engine try b four times?

    The greedy .* first takes everything to the end of the string, so b is tried at the end, then one character back, then another, and succeeds at the third character back. Each failure triggers one backtrack.

  2. 02What does a backtracking engine do when a match attempt starting at position 0 fails entirely?

    It advances the start position by one and tries the whole pattern again from there. It reports no match only after every start position has failed.

  3. 03/category|cat/ and /cat|category/ both appear to describe the same words. Why do they give different results on 'category'?

    Alternation in a backtracking engine is ordered. The first branch that lets the whole pattern succeed wins, so the first pattern returns category and the second returns cat. Put longer alternatives first.

  4. 04Which is cheaper on a string with a quoted word, ".*?" or "[^"]*", and why?

    The negated class. It stops at the first closing quote on its own, with no backing off. The lazy dot extends one character at a time and re-checks the closing quote after each, so it did 6 steps to the class's 4 in my trace.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark