Python re Module
In this page:
Searching for Patterns
The re module implements regular-expression pattern matching over strings. re.search() scans the whole string looking for the first location where the pattern matches anywhere, and returns a match object (or None if nothing matched) -- unlike re.match(), which only checks for a match starting at the very beginning of the string.
Example: Searching for Patterns
import re
match = re.search(r"\d+", "Order 42")
print(match.group())
Finding All Matches
re.findall() scans the entire string and returns every non-overlapping match as a list of strings, which is the simplest way to pull out every occurrence of a pattern at once rather than looping and calling search() repeatedly.
Example: Finding All Matches
import re
print(re.findall(r"\d+", "10 apples 20 oranges"))
Replacing Strings with sub()
re.sub(pattern, replacement, string) finds every match of the pattern and replaces it with the given replacement text, returning a new string -- the original string is left unmodified since Python strings are immutable. It's the standard tool for bulk find-and-replace operations that go beyond plain substring matching.
Example: Replacing Strings with sub()
import re
print(re.sub(r"\d", "#", "Call 123"))
Using Regex Groups
Wrapping part of a pattern in parentheses () creates a capturing group, letting you pull out specific sub-pieces of a match -- like extracting just the domain from a matched email address -- rather than only getting the whole matched text back.
Example: Using Regex Groups
import re
match = re.search(r"(\w+)@(\w+)\.com", "[email protected]")
print(match.group(1), match.group(2))
Compiling Regex Patterns
re.compile() pre-compiles a pattern string into a reusable regex object with its own .search()/.match()/.findall() methods. Compiling once and reusing the object avoids Python re-parsing the same pattern string on every call, which matters when you're applying the same pattern across a large loop or dataset.
Example: Compiling Regex Patterns
import re
pattern = re.compile(r"\d+")
print(pattern.findall("10 apples 20 oranges"))
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: