Python theorytheory 0/50 · 0%
Strings · medium

27. Regular expressions

Pattern matching text with the re module.

The `re` module matches patterns in text. `re.match` anchors at the start, `re.search` finds anywhere, and `re.findall` returns all matches.

python
import re

pattern = r"^0x[a-fA-F0-9]{40}$"
bool(re.match(pattern, "0x" + "a" * 40))   # True

re.findall(r"\d+", "block 100, tx 42")     # ["100", "42"]
re.sub(r"\s+", " ", "too   many   spaces")  # "too many spaces"

Raw strings (`r"..."`) avoid double-escaping backslashes in patterns. Named groups `(?P<name>...)` let you extract structured pieces via `match.group("name")`.

Check your understanding

  1. 1. What is the purpose of a raw string prefix `r"..."` in regex?

  2. 2. What does `re.findall(r'\\d+', text)` return?

  3. 3. What does `re.match` check, unlike `re.search`?