Python Regular Expressions
In this page:
The re Module
Regular expressions describe text patterns you can search, validate, or extract with, and Python exposes them through the built-in re module rather than a separate library. They're the standard tool any time you need to check a format (like an email address) or pull structured pieces out of free-form text.
Example: The re Module
import re
match = re.search(r"\d+", "Order 42 shipped")
print(match.group())
Finding All Matches
re.findall() scans the whole string and returns every non-overlapping match as a list, which makes it the go-to choice when you care about all occurrences rather than just the first one. If your pattern has capturing groups, findall() returns tuples of the group contents instead of full matches.
Example: Finding All Matches
import re
numbers = re.findall(r"\d+", "10 apples, 20 oranges")
print(numbers)
Search and Match
re.search() looks anywhere in the string and stops at the first match, while re.match() only succeeds if the pattern matches starting at index 0 -- a common bug is using match() and being confused when a valid pattern fails simply because it wasn't at the very start.
Example: Search and Match
import re
print(re.search(r"World", "Hello World"))
print(re.match(r"World", "Hello World"))
Substituting Text
re.sub() finds every match of a pattern and replaces it with a new string (or the result of a function), which is how most text-cleaning pipelines strip HTML tags, normalize whitespace, or mask sensitive data like phone numbers.
Example: Substituting Text
import re
text = "Call 123-456-7890"
masked = re.sub(r"\d", "*", text)
print(masked)
Splitting by Pattern
re.split() breaks a string into a list wherever the pattern matches, which is more flexible than str.split() since the delimiter itself can be a pattern -- for example splitting on any run of one or more commas and spaces at once.
Example: Splitting by Pattern
import re
parts = re.split(r",\s*", "a, b,c, d")
print(parts)
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: