← Back to Python Course | Chapter 5: Strings | Lesson 5 of 6

Python Regular Expressions

A regular expression is a special search pattern, like a metal detector tuned to find one kind of thing. It lets you find or replace text that follows a certain shape, such as phone numbers.
Syntax
python
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

python
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

python
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

python
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

python
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

python
import re
parts = re.split(r",\s*", "a, b,c,  d")  # splits on a comma plus any following spaces
print(parts)
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. Using re.match() when you mean re.search(), since match only checks the start of the string and returns None if the pattern appears later.
  2. Writing patterns without a raw string, as in "\d+", instead of r"\d+", which triggers escape-sequence warnings and can change meaning.
  3. Using the result without checking for None, so re.search(...).group() raises AttributeError when nothing matches.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

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.