Python intermediate: regular expressions (the re module)
Python re: search, match, findall, groups, and sub. Raw strings, when a regex is the wrong tool, official docs, and 20 exercises.
Getting started
Home Assistant
Buying
Python re: search, match, findall, groups, and sub. Raw strings, when a regex is the wrong tool, official docs, and 20 exercises.


AI-generated illustration
Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.
Direct answer (November 2026) — Use the
remodule with raw strings (r"...") to search (search), anchor at the start (match), list matches (findall), or replace (sub). Keep patterns simple, and write the intent in a comment.
A regular expression (regex) is a compact notation for a family of possible strings: “a run of digits,” “a word made of letters,” “a date in YYYY-MM form,” and so on. The standard re module compiles those patterns and applies them with search, split, or replace functions. It is very effective on semi-structured text (logs, exports). Complex patterns quickly become hard to read and hard to maintain. The rule of thumb: stay simple, name the intent in a comment, and consider a parser (HTML, JSON, or CSV with the csv module) when the format is rich or still changing.
This lesson is part of intermediate Python — after tests and code quality, and before other modules on the programming track.
search vs matchre.search(pattern, text) walks the whole string and returns the first match. re.match(pattern, text) tests only the start of the string (as if the pattern were implicitly anchored at the beginning). It matches the same text as search only when the pattern matches from the first character.
import re
m = re.search(r"\d+", "abc123def")
if m:
print(m.group()) # 123
Raw strings: prefer r"\d+" to "\\d+". The r prefix limits surprises with backslashes (\ as Python sees it, versus \ as the regex engine sees it).
findall and finditerfindall returns a list of matches (strings, or tuples when the regex contains groups). finditer yields Match objects one by one. Use it when you need positions (span()) or named groups without loading every match into memory at once.
re.findall(r"\w+", "a,b,c") # alphanumeric words plus _
subre.sub(pattern, replacement, text) applies a replacement (a string or a function) to each match. A classic example is collapsing repeated whitespace.
re.sub(r"\s+", " ", "a b c") # a single space between words
Parentheses in the pattern define capturing groups: m.group(1) is the first pair, and so on. Named groups (?P<name>...) make longer patterns easier to read.
m = re.match(r"(\d+)-(\d+)", "2026-03")
m.group(1), m.group(2)
Limits: validating an email or a URL “perfectly” with one regex is hard and often imprecise. In production you combine a coarse regex with business validation or a proven library. For HTML or JSON, do not use a regex as the main parser.
The exercises stay on short patterns. Solutions are hidden by default.
Exercise 1 — Find the first digit with re.search(r"\d", s) on "a7b". Easy
import re
m = re.search(r"\d", "a7b")
print(m.group())
Exercise 2 — re.findall(r"\d+", "price 12 and 3"). Easy
import re
print(re.findall(r"\d+", "price 12 and 3"))
Exercise 3 — Replace repeated spaces with one space using re.sub. Easy
import re
s = re.sub(r"\s+", " ", "a b")
print(s)
Exercise 4 — re.match(r"hi", "hi there"): what does group() return? Easy
import re
m = re.match(r"hi", "hi there")
print(m.group()) # hi
Exercise 5 — Why does re.match fail to find "x" in "ax"? Easy
# match anchors at the start of the string; use search to look anywhere.
Exercise 6 — Find "cat" or "dog" with re.search(r"cat|dog", s). Easy
import re
print(re.search(r"cat|dog", "my dog").group())
Exercise 7 — re.IGNORECASE ignores case: re.search(r"abc", "ABC", re.I). Easy
import re
print(re.search(r"abc", "ABC", re.I).group())
Exercise 8 — A capturing group: re.match(r"(\d{4})-(\d{2})", "2026-03"), then groups(). Intermediate
import re
m = re.match(r"(\d{4})-(\d{2})", "2026-03")
print(m.groups())
Exercise 9 — A simplistic email pattern r"[\w.+-]+@[\w-]+\.\w+". State why it is not enough in production. Intermediate
# Edge cases (IDN, +, comments); prefer a library or server-side validation.
Exercise 10 — re.split(r"[;,]", "a;b,c"). Intermediate
import re
print(re.split(r"[;,]", "a;b,c"))
Exercise 11 — re.fullmatch(r"\d+", "1234") for the entire string. Intermediate
import re
print(re.fullmatch(r"\d+", "1234") is not None)
Exercise 12 — re.sub(r"(\w+)", r"[\1]", "a b"). Understand the backreference \1. Intermediate
import re
print(re.sub(r"(\w+)", r"[\1]", "a b"))
Exercise 13 — Compile a pattern with re.compile(r"\d+") and reuse .search. Intermediate
import re
pat = re.compile(r"\d+")
print(pat.search("x99").group())
Exercise 14 — Best practice: why limit the length of the text before a heavy regex on a file? Intermediate
# Risk of catastrophic backtracking (ReDoS) on poorly chosen patterns.
Exercise 15 — Extract every simplified http... URL with findall (a minimal pattern). Hard
import re
texte = "see http://ex.com and https://a.org"
print(re.findall(r"https?://\S+", texte))
Exercise 16 — re.DOTALL: what does the flag do for .? Hard
# The dot also matches a newline.
Exercise 17 — On the string "2026-03", use a named group for the year (a pattern of the form (?P<year>\d{4})), then print the year with m.group("year"). Hard
import re
# Named group "year" (syntax: (?P<name>...) in the Python "re" docs)
m = re.match(r"(?P<year>\d{4})-(\d{2})", "2026-03")
print(m.group("year"))
Exercise 18 — Escape a literal dot: match "3.14" with r"\d+\.\d+". Hard
import re
print(re.fullmatch(r"\d+\.\d+", "3.14"))
Exercise 19 — re.escape("a+b"): what is it for? Hard
import re
# Escape metacharacters so a user string is searched for literally.
print(re.escape("a+b"))
Exercise 20 — A function masquer_emails(texte) that replaces user@domain.tld with user@*** using re.sub (a simple pattern). Hard
import re
def masquer_emails(texte): return re.sub(r”([\w.+-]+)@([\w.-]+)”, r”\1@***”, texte)
Back to the intermediate Python hub · Lesson 5 — tests · guided projects (battleship, hangman, and more).
Python text-processing books:
Check today’s price on Amazon
Was this page helpful?
Thank you!
What should we improve?
Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.
Cookies and analytics
We use Google Analytics 4 to understand how the site is used (page views, navigation). It is only switched on if you accept. Declining does not stop you using the site. More: cookie settings and privacy policy (in French).