Python Regular Expressions
In this page:
import re
re.search(pattern, string)
re.findall(pattern, string)
re.sub(pattern, replacement, string)
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") # finds the first run of digits
print(match.group()) # the matched text itself
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") # returns every match as a list
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")) # search() finds it anywhere in the string
print(re.match(r"World", "Hello World")) # match() fails since "World" isn't at index 0
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) # replaces every digit with an asterisk
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") # splits on a comma plus any following spaces
print(parts)
- Using
re.match()when you meanre.search(), sincematchonly checks the start of the string and returnsNoneif the pattern appears later. - Writing patterns without a raw string, as in
"\d+", instead ofr"\d+", which triggers escape-sequence warnings and can change meaning. - Using the result without checking for
None, sore.search(...).group()raisesAttributeErrorwhen nothing matches.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: