← Back to Python Course | Chapter 12: Standard Library | Lesson 6 of 9

Python re Module

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

python
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

python
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()

python
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

python
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

python
import re
pattern = re.compile(r"\d+")
print(pattern.findall("10 apples 20 oranges"))

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.