Skip to content

Lesson 33 of 52Python power tools

Regular Expressions

Use Python's re module well: search vs match vs fullmatch, the findall group trap, sub with functions, verbose patterns, and how to avoid ReDoS.

17 min read0/4 questions

A support engineer pastes 40,000 lines of access logs into a ticket and asks which IPs are hammering the login endpoint. A product manager wants every order reference (ORD- plus six digits) pulled out of a pile of customer emails. A form needs to reject postcodes that are obviously wrong. These are the jobs where a regular expression earns its place: finding, extracting and validating text with a shape. Python's re module does all of it, but it has its own API traps that bite even people who know regex well from another language. This lesson is about those Python specifics. For the shared theory (greedy versus lazy, lookaround, how a backtracking engine works) the JavaScript & TypeScript course's Regular Expressions lesson goes deeper, and everything there applies here too.

When not to use a regex

Reach for plain string methods first. They are faster to read, faster to run, and cannot backtrack:

JobBetter than a regex
Does it start or end with something?s.startswith(("http://", "https://")), s.endswith(".csv")
Does it contain a substring?"ERROR" in line
Split on one fixed separatorline.split(","), s.partition("=")
Strip a known prefixs.removeprefix("Bearer ")
Is it all digits?s.isdigit() (careful: also true for other scripts' digits)

And reach for a real parser when the format is nested or has quoting rules. CSV has quoted fields with commas inside them (csv module). JSON, HTML, XML, URLs and dates all have parsers in the standard library or a well-known package (json, html.parser, urllib.parse, datetime.fromisoformat). A regex that "parses HTML" works on the three examples you tried and breaks in production.

Regex is the right tool when the text is flat but the pattern is not a fixed string: log lines, IDs with a format, extraction from free text, quick validation of simple formats.

Raw strings, and why "\b" is a backspace

Python processes backslashes in normal string literals before re sees the pattern. "\b" in Python source is a single backspace character, while the regex \b means "word boundary". So a pattern written without the r prefix can silently mean something else:

Python
import re print(len("\b"), len(r"\b"))print(re.findall("\bcat\b", "cat scat cat")) # "\b" here is a backspace characterprint(re.findall(r"\bcat\b", "cat scat cat")) # raw string: a word boundaryprint(re.findall(r"\d+", "Order ٣٤ shipped in 2 days"))print(re.findall(r"\d+", "Order ٣٤ shipped in 2 days", re.ASCII))
Output
Press Run (⌘ Enter) to see what happens.

The first findall finds nothing and raises no error. Escapes that are not valid in Python strings, like "\d", at least produce a SyntaxWarning since 3.12, but \b is valid, so you get no warning at all. The rule is simple: every pattern is a raw string, r"...".

The last two lines show the other Python surprise. Patterns on str are Unicode-aware by default. \d matches any Unicode decimal digit, including Arabic-Indic ٣٤, and \w matches letters with accents like é. That is usually what you want for names, and usually not what you want when validating something that must be ASCII, like a card number you then pass to int() or a bank API. Add re.ASCII (or write [0-9]) when that matters.

The syntax you need, in one table

Python's syntax is close to every other modern regex flavour. A quick refresher, with the Python-specific rows marked:

PatternMeaning
.Any character except newline (any at all with re.S)
[a-z0-9_], [^,]One character from the set, or not in it
\d \w \s and \D \W \SDigit, word character, whitespace, and their opposites. Unicode by default in Python
* + ? {3} {2,5}Repeat: 0+, 1+, 0 or 1, exactly 3, 2 to 5. Add ? for lazy, + for possessive (3.11+)
^ $Start and end of string (of each line with re.M). $ also matches before a final newline
\A \ZAbsolute start and end, never affected by re.M. \z also works since 3.14
\bWord boundary
(...), (?:...)Capturing group, non-capturing group
(?P<name>...), (?P=name)Named group and a backreference to it. Python needs the P
(?=...) (?!...) (?<=...) (?<!...)Lookahead and lookbehind. Lookbehind must be fixed width in re
(?>...)Atomic group (3.11+): once matched, never backtracked into

Two rows deserve a closer look. (?<name>...) without the P, which JavaScript and .NET use, is a re.error in Python. And unlike JavaScript, re rejects variable-width lookbehind such as (?<=\d+): "look-behind requires fixed-width pattern".

match, search and fullmatch

This is the most common re bug in code review. The three functions differ only in where the match is allowed to be:

  • re.search(p, s) finds the first match anywhere in s. This is what most other languages call "match".
  • re.match(p, s) only tries at position 0. It does not require the match to reach the end.
  • re.fullmatch(p, s) requires the pattern to cover the entire string. Use it for validation.
Python
import re code = "AB-1234"print(re.match(r"\d+", code)) # only tries position 0print(re.search(r"\d+", code)) # first match anywhereprint(re.fullmatch(r"[A-Z]{2}-\d{4}", code)) sneaky = "AB-1234\n"print(bool(re.match(r"^[A-Z]{2}-\d{4}$", sneaky))) # $ also matches before a final \nprint(bool(re.fullmatch(r"[A-Z]{2}-\d{4}", sneaky)))print(bool(re.match(r"[A-Z]{2}-\d{4}\Z", sneaky)))
Output
Press Run (⌘ Enter) to see what happens.

The second half is a real security-relevant trap. In Python, $ matches at the end of the string or just before a newline at the end. Validating with ^...$ lets "AB-1234\n" through, and that trailing newline can end up in a header, a filename or a log line. fullmatch (or \Z) has no such exception.

Where can the pattern end on "AB-1234\n"?
A
0
B
1
-
2
1
3
2
4
3
5
4
6
\n
7
pattern = [A-Z]{2}-\d{4}pos = 7

The body of the pattern consumes the first seven characters. The engine is now at position 7, just before the newline.

1/4

Python 3.15 adds re.prefixmatch() as a clearer name for re.match() and soft-deprecates match. Nothing breaks: soft deprecation means the old name stays, but new code on 3.15 can say what it means. On 3.14 and earlier, keep using match and remember what it does.

Quick check
You must accept an order code only if the whole input is ORD- followed by exactly six digits. Which call is correct?
Need a nudge? A hint rules out a wrong answer.

findall, finditer and the match object

re.findall has one behaviour that surprises everyone: what it returns depends on the number of groups in the pattern.

Python
import re log = "user=ada id=17 user=sam id=9 user=leo" print(re.findall(r"user=\w+", log)) # no groups: whole matchesprint(re.findall(r"user=(\w+)", log)) # one group: just the groupprint(re.findall(r"user=(\w+) id=(\d+)", log)) # several groups: tuples for m in re.finditer(r"user=(?P<name>\w+) id=(?P<id>\d+)", log): print(m.span(), m["name"], m.groupdict()) m = re.search(r"id=(\d+)", log)print(m.group(0), m.group(1), m.start(1), m.end(1))print(re.search(r"id=(\d+)", "no ids here"))
Output
Press Run (⌘ Enter) to see what happens.

No groups returns whole matches. One group returns only that group. Several groups return tuples. So adding parentheses for grouping, like (https?)://\S+, suddenly turns your list of URLs into a list of "http" and "https". The fix is a non-capturing group: (?:https?)://\S+.

For anything beyond a quick list, use re.finditer. It yields Match objects lazily, which is better for large inputs, and a match object gives you everything: m[0] or m.group(0) for the whole match, m["name"] for a named group, m.groupdict() for all named groups as a dict, and m.start(), m.end(), m.span() for positions. Unmatched optional groups come back as None.

search, match and fullmatch return None when nothing matches, so always check before you index. With type hints, the checker forces this: the return type is re.Match[str] | None. The idiom is if (m := pattern.search(line)) is not None:.

Predict the outputPython

What does this print?

import re
print(re.findall(r"(\w+)=(\d+)", "a=1 b=x c=3"))
Need a nudge? Hints walk you through it.

sub, subn and split

re.sub replaces matches. The replacement can be a string, where \1 or \g<name> refers to a group, or a function that receives each Match and returns the replacement text. The function form is how you do anything that needs logic: unit conversion, lookups, redaction that keeps the last four digits.

Python
import re prices = "Tea 2.50 GBP, cake 3.10 GBP, delivery 0 GBP" def to_pence(m: re.Match[str]) -> str: pence = round(float(m["amount"]) * 100) return f"{pence}p" print(re.sub(r"(?P<amount>\d+(?:\.\d+)?) GBP", to_pence, prices))print(re.sub(r"(\d{2})/(\d{2})/(\d{4})", r"\3-\2-\1", "due 31/12/2026"))print(re.sub(r"\s+", " ", "too many\n\tspaces"))print(re.subn(r"\d", "#", "pin 4321")) print(re.split(r"\s*[,;]\s*", "a, b;c ,d"))print(re.split(r"(\s*[,;]\s*)", "a, b;c")) # a group keeps the separators
Output
Press Run (⌘ Enter) to see what happens.
  • Write the replacement as a raw string too, r"\3-\2-\1", for the same backslash reason.
  • \g<1> is the unambiguous form of \1, needed when a digit follows: r"\g<1>0" means "group 1 then a zero", while r"\10" means group 10.
  • subn returns (new_string, count), which is handy for logging how many secrets you redacted.
  • re.split with a capturing group keeps the separators in the result. Pass maxsplit= to stop early.

compile, flags and verbose patterns

re.compile(pattern, flags) returns a Pattern object with the same methods (pattern.search(s), pattern.sub(...)). The module also keeps a cache of recently used patterns, so the speed gain from compiling is small. The real reasons to compile are readability and reuse: a named module-level constant like ORDER_REF = re.compile(...) documents itself and fails at import time if the pattern is invalid.

The flags you will use, combined with |:

Match the pairs0/5 matched

Match each flag to what it changes.

Choose an item, then its match on the other side.

re.VERBOSE is the most underused feature in the module. It lets a long pattern span several lines with comments, which turns an unreadable one-liner into something a reviewer can check. Here is a real access log parser:

Python
import re LINE = re.compile( r""" (?P<ip>\d{1,3}(?:\.\d{1,3}){3}) # client IPv4 address \s-\s(?P<user>\S+)\s # ident is always "-", then user or "-" \[(?P<time>[^\]]+)\]\s # [22/Oct/2026:10:15:32 +0000] "(?P<method>[A-Z]+)\s(?P<path>\S+)\s(?P<proto>[^"]+)"\s (?P<status>\d{3})\s (?P<size>\d+|-) # "-" when no body was sent """, re.VERBOSE,) lines = [ '203.0.113.7 - - [22/Oct/2026:10:15:32 +0000] "GET /api/orders?page=2 HTTP/1.1" 200 5123', '198.51.100.23 - ada [22/Oct/2026:10:15:33 +0000] "POST /api/login HTTP/1.1" 401 -', 'garbage line from a health check',] for line in lines: m = LINE.fullmatch(line) if m is None: print("unparsed:", line[:30]) continue row = m.groupdict() row["status"] = int(row["status"]) row["size"] = 0 if row["size"] == "-" else int(row["size"]) print(row["ip"], row["method"], row["path"], row["status"], row["size"], row["user"])
Output
Press Run (⌘ Enter) to see what happens.

Notice the habits: named groups so the result is a dict, [^\]]+ and [^"]+ (negated classes) instead of .*? so each part cannot overrun into the next, fullmatch so a partial match does not count, and an explicit branch for lines that do not parse. Count unparsed lines in real scripts. A silent 5% parse failure is how log reports go wrong. In verbose mode, literal spaces must be written as \s or [ ], because plain spaces are ignored.

Two everyday helpers, and the email trap

Python
import reimport unicodedata def slugify(title: str, max_len: int = 60) -> str: text = unicodedata.normalize("NFKD", title) text = text.encode("ascii", "ignore").decode("ascii") # drop accents text = re.sub(r"[^\w\s-]", "", text.lower()) # drop punctuation text = re.sub(r"[\s_-]+", "-", text).strip("-") # collapse separators return text[:max_len].rstrip("-") print(slugify(" Café Opening: 50% off -- Today! "))print(slugify("Python 3.14 & the new annotationlib")) EMAIL = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")text = "Contact ada@example.com or sam.lee+billing@mail.example.co.uk, not @here or a@b."print(EMAIL.findall(text))
Output
Press Run (⌘ Enter) to see what happens.

The email pattern is deliberately rough. It is fine for pulling likely addresses out of text for a human to review. It is not a validator. The real address grammar allows quoted local parts, comments and international domains, and the "complete" regexes that try to cover it run to thousands of characters and are still wrong. To validate an address, check for one @ with something on each side (a library like email-validator or Pydantic's EmailStr does it properly), then send a confirmation email. That is the only check that proves the address works.

Catastrophic backtracking and ReDoS

Python's re is a backtracking engine, like JavaScript's. A pattern where the same characters can be matched in many ways, such as the nested (a+)+, can take exponential time on input that almost matches. The TypeScript lesson walks through exactly why, step by step. Here is the Python version of the experiment:

Python
import reimport time nested = re.compile(r"^(a+)+$")possessive = re.compile(r"^(a++)+$")atomic = re.compile(r"^(?>a+)+$")flat = re.compile(r"^a+$") for n in [16, 18, 20, 22]: text = "a" * n + "!" row = [] for name, pat in [("nested", nested), ("possessive", possessive), ("atomic", atomic), ("flat", flat)]: t0 = time.perf_counter() pat.match(text) row.append(f"{name} {(time.perf_counter() - t0) * 1000:7.2f} ms") print(f"n={n}:", " | ".join(row))
Output
Press Run (⌘ Enter) to see what happens.

Each extra two characters makes the nested pattern about four times slower. At 30 characters it takes seconds; at 40, longer than anyone will wait. During that time, the match runs in C and cannot be interrupted: a web worker handling the request is stuck, and in an async app the whole event loop stops serving every other user. That is ReDoS, regular expression denial of service.

Python-specific defences, in order:

  1. Rewrite so each character can only be matched one way: ^a+$, or negated classes like [^,]* instead of .*.
  2. Possessive quantifiers (a++, \d*+) and atomic groups ((?>...)), new in Python 3.11, tell the engine never to give characters back once taken. They make the nested pattern above instant. They also change what can match, so test them.
  3. Limit input length before matching. Validating a 200-character field never needs to look at 2 MB of input. The stdlib re has no timeout.
  4. For patterns supplied by users, use the third-party regex package, which accepts a timeout= argument, or a linear-time engine such as Google's RE2 through its Python bindings. Check each package's docs for current details.
Quick check
A FastAPI endpoint validates a tags field with re.fullmatch(r"(\w+,?)+", value). Some requests hang for seconds. What is the best first fix?
Need a nudge? A hint rules out a wrong answer.
Key terms
raw string
A literal like r"\d+" where backslashes are kept as-is, so they reach re unchanged.
fullmatch
Succeeds only if the pattern matches the entire string. The right call for validation.
Match object
What search, match, fullmatch and finditer return: groups, groupdict(), and positions via span().
named group
(?P<name>...): a capture you read as m["name"] or via groupdict().
re.VERBOSE
A flag that ignores whitespace and allows # comments, so long patterns can be laid out and documented.
possessive quantifier
a++, a*+ (3.11+): matches greedily and never backtracks, which blocks catastrophic backtracking.
ReDoS
Denial of service caused by input that makes a backtracking regex run for exponential time.