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.

Loupe éclairant un motif dans une grille de symboles, illustrant la recherche de motifs avec les expressions régulières

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 re module 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.

1. Search: search vs match

re.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).

2. Every match: findall and finditer

findall 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 _

3. Replace: sub

re.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

4. Groups and extraction

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.

External resources

Exercises (20)

The exercises stay on short patterns. Solutions are hidden by default.

Easy level

Exercise 1 — Find the first digit with re.search(r"\d", s) on "a7b". Easy

Show the solution
import re
m = re.search(r"\d", "a7b")
print(m.group())

Exercise 2 — re.findall(r"\d+", "price 12 and 3"). Easy

Show the solution
import re
print(re.findall(r"\d+", "price 12 and 3"))

Exercise 3 — Replace repeated spaces with one space using re.sub. Easy

Show the solution
import re
s = re.sub(r"\s+", " ", "a    b")
print(s)

Exercise 4 — re.match(r"hi", "hi there"): what does group() return? Easy

Show the solution
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

Show the solution
# 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

Show the solution
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

Show the solution
import re
print(re.search(r"abc", "ABC", re.I).group())

Intermediate level

Exercise 8 — A capturing group: re.match(r"(\d{4})-(\d{2})", "2026-03"), then groups(). Intermediate

Show the solution
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

Show the solution
# Edge cases (IDN, +, comments); prefer a library or server-side validation.

Exercise 10 — re.split(r"[;,]", "a;b,c"). Intermediate

Show the solution
import re
print(re.split(r"[;,]", "a;b,c"))

Exercise 11 — re.fullmatch(r"\d+", "1234") for the entire string. Intermediate

Show the solution
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

Show the solution
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

Show the solution
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

Show the solution
# Risk of catastrophic backtracking (ReDoS) on poorly chosen patterns.

Hard level

Exercise 15 — Extract every simplified http... URL with findall (a minimal pattern). Hard

Show the solution
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

Show the solution
# 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

Show the solution
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

Show the solution
import re
print(re.fullmatch(r"\d+\.\d+", "3.14"))

Exercise 19 — re.escape("a+b"): what is it for? Hard

Show the solution
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

Show the solution
import re

def masquer_emails(texte): return re.sub(r”([\w.+-]+)@([\w.-]+)”, r”\1@***”, texte)

Next in the series

Back to the intermediate Python hub · Lesson 5 — tests · guided projects (battleship, hangman, and more).

Free resources (nothing to buy)

Amazon (affiliate, optional)

Python text-processing books:

Check today’s price on Amazon

Further reading

Was this page helpful?

Have a question about this guide or need advice? Ask us here

Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.