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

Python re Module

The re module is Python's tool for pattern searching in text, like a detective following clues shaped a certain way. You use it to find, check, or replace pieces of text.
Syntax
python
import re

match = re.search(pattern, string)
if match:
    match.group()

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")  # finds the pattern anywhere in the string
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))  # group(1) and group(2) are the parenthesized captures

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+")  # compiled once, reusable across many calls
print(pattern.findall("10 apples 20 oranges"))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting the raw-string prefix, as in "\d+" instead of r"\d+", which produces warnings and wrong patterns.
  2. Using re.match() when the pattern can appear anywhere; re.search() looks through the whole string.
  3. Using a greedy pattern like .* and capturing far more than intended; use .*? for the shortest match.

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.