Skip to content

Lesson 1 of 9 · 24m

The Regex Engine Mental Model: Search, Not Magic

Understand how Python's regex engine scans, chooses alternatives, backtracks, and commits to a match so counterintuitive behavior becomes predictable.

The worst regex bugs I have inherited were written by smart people who thought regex was a declarative language. It is not. A regex is a small program executed by a backtracking engine, scanning text left to right and undoing choices when a path fails. Once you see the machine, the behavior stops being spooky.

Python's re engine backtracks

The engine tries one path, remembers alternatives, and rewinds when the path fails:

import re

pattern = re.compile(r"a(bc|b)c")
print(pattern.search("abc"))   # succeeds through the second branch

It first tries bc, reaches the final c, fails, rewinds, tries b, and succeeds. That is normal here. In a pathological pattern, the same rewind can happen millions of times.

Position is part of the contract

re.match anchors implicitly at the beginning of the string. re.search scans for the first position where the pattern can start. fullmatch requires the whole value:

text = "error code=418 retrying"
print(re.match(r"code=(\d+)", text))   # None: not at position 0
print(re.search(r"code=(\d+)", text))  # matches at position 6

A validation rule written with search often accepts garbage before or after the intended value. A parsing rule written with match often misses values embedded in text. Choose the API deliberately.

The first match is not the smartest match

Regex does not rank answers by usefulness. It finds the first leftmost match the engine can construct:

print(re.search(r"cat|catalog", "catalog").group())  # 'cat'
print(re.search(r"catalog|cat", "catalog").group())  # 'catalog'

Ordering is semantics. Alternation is not a set of equals, and the engine does not automatically prefer the longest branch.

Greed means prefer more, then retreat

Greedy quantifiers consume as much as possible and only retreat if the rest of the pattern cannot match:

html = "<b>one</b><b>two</b>"
print(re.search(r"<b>.*</b>", html).group())   # '<b>one</b><b>two</b>'
print(re.search(r"<b>.*?</b>", html).group())  # '<b>one</b>'

Lazy .*? is not automatically safer. It changes what is preferred, not what is possible, and it may scan character by character across huge input. Precision beats laziness: [^<]* often says what you actually meant.

Field notes

  • re.match is not the same as ^ plus re.search when multiline mode is involved.
  • The leftmost match wins even when a later match looks more useful.
  • Alternation order changes results; regex engines do not choose the longest branch automatically.
  • Greedy and lazy quantifiers differ in preference, not in ultimate expressive power.
  • Use fullmatch for validation. Anchors inside search are a common source of accidental acceptance.

Was this lesson helpful?

Sign in to rate