Regular expressions
Match, find and replace text patterns with the re module.
- 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
- 1Import re, then describe the pattern inside a raw string like r"[0-9]+".
- 2Use re.search to find one match and .group() to get it.
- 3Use re.findall to collect every match into a list.
- 4Use re.sub to swap matches for replacement text.
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.
Count the digits
Count how many digit characters are in the sentence and print the total.
import re
sentence = "Room 12 has 3 desks and 24 chairs"
Which function replaces every match with new text?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.