Regular expressions

O(n · m)·O(n + m) stack depth space
sequence, position 0sequenceposition 0
  • Active

Trying sequence at position 0.

Trying sequence at position 0.
  1. 1try the next choice at this point in the pattern
  2. 2everything after it matched too: keep this choice
  3. 3something after it failed: undo this choice and try the next one
  4. 4finished: the text matches if every choice ran out together with the text
Attempts (the path count)
1
Attempts resolved
0
Character comparisons
0

Complexity

BestO(n)
AverageO(n · m)
Worstexponential in the input
Extra spaceO(n + m) stack depth
attempts at n=9 predicts 27; this run took 1.

Naive backtracking

The naive matcher tries a pattern against a text the way a person reading the pattern aloud might: take the next piece of the pattern, try to match it, and if everything after it also works out, you are done — otherwise go back and try a different choice at the last place one was available (a quantifier choosing to stop, or an alternation choosing a different branch). This is what a hand-written matcher, and many standard-library engines, implement by default — it is simple, and it is exactly as correct as the automaton pages, but it has no bound on how many times it might have to retry.

When it is the right choice

This is almost always fine: most patterns and most inputs give the matcher very little to backtrack over, and this is the algorithm behind back-references and lookaround, which the automaton pages cannot run at all. The danger is specific and well known: a quantified group nested inside another quantifier, asked to match an input that ultimately fails. Every way the outer quantifier could have split the input between its repetitions gets tried before the engine can conclude there is no match — and the number of ways to split n identical characters grows exponentially in n.

How it works

Worth noticing

Cost

Best
O(n)
Average
O(n · m)
Worst
exponential in the input
Extra space
O(n + m) stack depth

The pattern is capped at 14 characters and the text at 24, both pedagogical rather than technical: every extra pattern character can roughly double the automaton this tool draws, and this page's own attempt count is bounded separately, by counting how many attempts a run would make before drawing a single one — an ordinary pattern and text pass easily, and a pattern shaped like the catastrophic example is refused outright once it would take more than a few thousand attempts to watch.

Worth comparing

All regex algorithms