Backtracking is a matching strategy that tries alternative paths. Ambiguous repetition can make the number of attempted paths grow very quickly.
Recognize risky shapes, understand the limits of warning heuristics and choose a scanner or bounded execution where appropriate.
A pattern matches short valid inputs quickly, then stalls on a nearly valid one. The failure path can explore many different ways to divide the same characters. We will count that ambiguity, compare a less ambiguous pattern, and identify what a small risk heuristic cannot guarantee.

Quarry has a feature request from operations: let us type our own search
patterns. A reasonable ask — and it hides the most famous performance bug in
text processing. This lesson measures that blow-up on your own machine,
explains exactly where it comes from, and builds safe_match(): a teaching heuristic for identifying a limited set of risky patterns. It
is not sufficient protection for accepting arbitrary operator patterns.
Let operators search the yard with their own pattern
Here's a pattern that looks harmless: (a+)+b — "one or more runs of a's,
then a b". Against a string of a's that ends in c instead of b, it has to
fail. Time how long failing takes:
Read your own numbers down the right column: every two extra characters
roughly quadruple the time — the signature of 2ⁿ. Now run the same
experiment with the pattern rewritten as a+b, which accepts exactly the
same strings:
Much slower growth on this example. Same accepted strings, same answer, different search cost. Whatever's going on is about the shape of the pattern, not what it matches.
Remember the engine's rule: when something fails, it backtracks and tries
another way to consume the same text. (a+)+ has an enormous number of other
ways. For aaaa, the outer + can use one inner run of four, or 3+1, 1+3,
2+2, 2+1+1, 1+2+1, 1+1+2, or 1+1+1+1 — eight carvings, each one reaching the
end, finding c where it wanted b, and failing. The engine won't give up
until it has tried them all.
def carvings(n):
if n == 0:
return 1
return sum(carvings(n - first) for first in range(1, n + 1))
print(carvings(5), carvings(10))For an illustrative cost model—not a measured guarantee—at a million attempts per second, (a+)+b failing on n
characters takes about 2ⁿ microseconds:
| characters | time to fail |
|---|---|
| 20 | about 1 second |
| 26 | over a minute |
| 35 | about 9.5 hours |
A log line is often longer than that. The rewritten a+b fails in a few
dozen steps, well under a millisecond.
Preparing this topic’s interactive investigation…
Catch the risky shape before it ever runs
Catastrophic backtracking needs two ingredients: a repeated group —
(…)+, (…)* or (…){n,} — whose body can match the same text in more
than one way from one repetition to the next. (\w+\s?)* is a common
attempt at "words separated by spaces" that qualifies, because \s? is
optional, so abc can be one word or three. Compare \d+(?:,\d+)*: every
repetition must begin with a mandatory comma, so 12,345,6 only splits
one way. Safe.
That gives a rule Quarry can check mechanically: inside a repeated group,
if every element is itself optional or repeated, the group is dangerous. A
mandatory literal separator breaks the ambiguity. It's a heuristic — it
misses overlapping alternatives like (a|aa)+ — so it must not be treated as a complete safety check.
GROUP finds a parenthesised body with no parentheses inside it, followed by
a repeating quantifier, skipping over a ?: or ?P<name> prefix.
ATOM.findall turns the body into (atom, quantifier) pairs; if every pair
has a quantifier, this exercise flags the group. A + still requires at
least one occurrence; the important danger is ambiguous partitions, not
merely whether a character is optional.
import re
ATOM = re.compile(r"(\\.|\[[^\]]*\]|[^|])([+*?]|\{\d*,?\d*\})?")
print(ATOM.findall(r",\d+"))Three more defences belong beside the rewrite: bound the input length
(with a deliberately chosen bound, not an assumed safe line length); since Python 3.11,
possessive quantifiers and atomic groups (a++, (?>…)) never give back
what they took, so (?>a+)+b fails instantly; and, sometimes, don't use a
regex at all.
A warning heuristic is not an execution sandbox
The exercise keeps the name safe_match, but its output means only “passed these two preliminary checks”. The small GROUP/ATOM recognizer does not parse the full regex language or prove an execution-time bound. Overlapping alternatives, repeated searches and patterns it does not recognize can still be expensive. Invalid syntax can also raise re.error.
The counted carvings illustrate one source of exponential growth; they are not a profiler's exact count of every engine operation. Timing small samples is noisy. Look for growth as the failing input expands, and stop well before an expensive case freezes the runner. Do not test a hostile pattern on a giant string to find out whether the guard works.
A safer product decision starts with the actual search requirement. If users need literal text, use substring search. If they need known filters, provide reviewed patterns and bound both pattern and input sizes. If arbitrary regex is required, use an execution environment or engine with an explicit resource policy. A Python thread cannot be assumed to interrupt a blocked re match on demand; local process isolation is a different architecture and is not available in this browser runner.
Analyze without running: (a|aa)+b on a run of a characters followed by c has competing ways to divide the run, although the exercise's heuristic can miss it. Explain which two alternatives overlap. Then compare a+a with a++a on aa: the possessive version refuses to give a character back, changing the result. Atomic groups and possessive quantifiers are not mechanical “make faster” switches; verify that a rewrite still accepts the intended language.
Reference: Python's regex syntax, including atomic groups and possessive quantifiers.
When a scanner beats a regex
A regex is the right tool for a flat shape. It's the wrong one when a
plain string method will do ("ERROR" in line can't backtrack), when the
structure nests (balanced brackets, JSON — re can't count nesting
depth), when the rules are about meaning (valid dates, checksums), or
when the pattern has become unreadable.
A hand-written scanner — a loop with an index that looks at one character, decides what kind of token starts there, and consumes it — is longer than a regex but can run in linear time when each step advances and each character is examined only a bounded number of times. This one splits a tail into words, but has a bug:
The last word goes missing. Run it, find the line responsible, and fix it without changing how the loop scans.
The next lesson builds a real scanner for Quarry's log tails.
Quick practice
import re
print(bool(re.fullmatch(r"\d+(?:,\d+)*", "12,345,6")))import re
GROUP = re.compile(r"\((?:\?:|\?P<\w+>)?([^()]*)\)(?:[+*]|\{\d+,\d*\})")
ATOM = re.compile(r"(\\.|\[[^\]]*\]|[^|])([+*?]|\{\d*,?\d*\})?")
def is_risky(pattern):
for group in GROUP.finditer(pattern):
for branch in group.group(1).split("|"):
atoms = ATOM.findall(branch)
if atoms and all(q for _, q in atoms):
return True
return False
print(is_risky(r"(a|aa)+"))🎯 Your turn
Write safe_match(pattern, text, max_len), the guard every operator-supplied
pattern goes through. Check in this order and return one of four strings:
"too-long"iftextis longer thanmax_len,"risky-pattern"if the pattern has a repeated group in which every element is optional or repeated (use theGROUP/ATOMcheck from this lesson),- otherwise
"match"ifre.search(pattern, text)finds something, else"no-match".
safe_match(r"\d+ms", "took=312ms", 100)→"match"safe_match(r"(a+)+b", "aaaa", 100)→"risky-pattern"safe_match(r"ERROR", "all good", 100)→"no-match"
Hint — the two cheap checks come first so matching only runs after the exercise's preliminary checks. Passing those checks does not prove a pattern safe.
Then press ▶ Run and hit ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write carvings(n) returning the number of ways to cut a run of n identical characters into one or more non-empty consecutive pieces — the number of attempts (a+)+ makes on it. By convention carvings(0) is 1.
Write atoms(body) returning the atoms of a regex group body as a list of [atom, quantifier] pairs (lists, not tuples), using the lesson's ATOM pattern. The quantifier is "" when an atom has none.
Write is_risky(pattern): True when the pattern contains a repeated group (+, * or {n,} after it) with a branch in which every atom is quantified. Use the lesson's GROUP and ATOM patterns, which are provided.
Write tokenise(tail) without re, returning a list of [kind, text] tokens. Skip whitespace. = is ["EQ", "="]. A double quote starts a STRING running to the next double quote (or the end); its text excludes the quotes. A run of letters, digits and any of _.-:/@ is a NUMBER if it is digits with at most one decimal point and digits after it, otherwise a WORD. Any other character is ["OTHER", ch].
Write scan_fields(tail) returning a dict of every WORD = value sequence in the tail, using a scanner like the boss exercise's. Values are typed: a NUMBER becomes an int (or float if it has a decimal point); a WORD that is a duration — digits, optional decimals, then ms or s — is stored under key + "_ms" as whole milliseconds; a STRING or any other WORD stays a string. Tokens that are not part of a WORD = value triple are ignored.
Explain to a teammate why (\w+\s?)*$ can take minutes to fail on a 30-character line while \w+(?:\s\w+)*$ fails instantly, even though they are meant to accept the same kind of text. Mention what the engine is doing during those minutes.