Python Foundations·Python from zero

Regular expressions

Match, find and replace text patterns with the re module.

Beginner 13 min read Lesson 6 of 480 Challenge included
What you will be able to do
  • Match patterns with re.search
  • Collect matches with re.findall
  • Replace text with re.sub
  • Use character classes and anchors, and plain string methods when simpler

In plain English

A regular expression (regex for short) is a small pattern language for finding text that follows a rule. You write patterns with the re module: re.search finds the first match, re.findall returns every match and re.sub replaces matches. Square brackets create a character class that matches any one of the characters inside, and anchors like ^ (start) and $ (end) pin the match to a position. Regex is powerful but hard to read, so for simple checks plain string methods such as startswith are clearer.

Step by step

  1. 1Import re, then describe the pattern inside a raw string like r"[0-9]+".
  2. 2Use re.search to find one match and .group() to get it.
  3. 3Use re.findall to collect every match into a list.
  4. 4Use re.sub to swap matches for replacement text.
patterns.pyPython
import re

text = "Order 123 shipped, order 456 pending"

match = re.search(r"[0-9]+", text)
print(match.group())

numbers = re.findall(r"[0-9]+", text)
print(numbers)

masked = re.sub(r"[0-9]+", "###", text)
print(masked)

print(bool(re.search(r"^Order", text)))
print(bool(re.search(r"pending$", text)))

Common mistakes

  • Forgetting the r prefix on a pattern, so backslashes like \d are misread.
  • Expecting re.search to return a string; it returns a match object or None.
  • Using a greedy .* that matches far more than you intended.
  • Reaching for regex when a simple string method would be clearer.
Your turn

Count the digits

Easy

Count how many digit characters are in the sentence and print the total.

PYTHON · starter
import re

sentence = "Room 12 has 3 desks and 24 chairs"
Check your understanding before moving on.
Knowledge checkQuestion 1

Which function replaces every match with new text?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 6 of 480 · 0% of course