1s = "cat 42 dog 7"2re.search(r"dog", s)3re.search(r"\d", s)4re.search(r"\d+", s)5re.findall(r"\d+", s)6re.search(r"\d+$", s)7re.search(r"(dog|cat) (\d+)", s)8re.sub(r"\d", "#", s)9re.search(r"(\d+)+x", s)10"dog" in sre01234567891011end×2 per digit
Code card: the program; the highlighted line is the one runningCharacter boxes: the string s, index on topStrips: green = matched so far, red = a failed comparisonPointer and re engine: where the search is in the stringEach step highlights one line of the program. For a search, the pointer is the engine's place in the string: a green strip in front of a box means that character has matched so far, a red flash means a comparison failed. When a strip shrinks the engine is backtracking; when an attempt fails it moves one start index to the right. A token then carries the result back to the line. ␣ marks a space character. The nested repeat on line 9 fails, and on a long run of digits it would try every way to split them; the work doubles with each digit. The moving pointer shows how a backtracking engine searches. CPython's engine adds shortcuts, such as jumping straight to a place where the first character could match, so it may skip some of the tries drawn here; the results are the same.

Patterns

  1. A regular expression, or regex, is a pattern that describes text. Python's re module matches patterns against strings. Here s holds 12 characters, one per box, each with its index on top. Every pattern below is tried against this row.

Classes and repeats

Anchors, groups, sub

Use with care

Try it in the Python prompt

;; step 1/10 · line 1: s = "cat 42 dog 7"
>>> import re
>>> s = "cat 42 dog 7"
>>> len(s)
12
>>> s[7]
'd'

The r before each pattern makes a raw string, so the backslash in \d reaches the re module unchanged. Every line assumes import re at the top. The moving pointer shows how a backtracking engine searches. CPython's engine adds shortcuts, such as jumping straight to a place where the first character could match, so it may skip some of the tries drawn here; the results are the same.