Last modified: Nov 19, 2026
Python Regex: re Module Guide
Regular expressions are a powerful way to search and change text. Python ships with the re module for this job. This guide explains the basics with clear examples.
You will learn the common functions, the main patterns, and how to avoid common mistakes. Every example includes code and output.
What Is a Regular Expression?
A regular expression (regex) is a pattern that describes text. You use it to find, check, or replace parts of a string.
For example, the pattern \d+ matches one or more digits. The pattern [a-z]+ matches lowercase letters.
Regex is useful for tasks like validating input, pulling data from logs, and cleaning text. It pairs well with simple programs such as a Python simple calculator program that needs to read user input.
Getting Started with the re Module
First, import the module. It is part of the standard library, so no install is needed.
import re
# A simple pattern: find the word "cat"
text = "The cat sat on the mat"
match = re.search(r"cat", text)
print(match.group()) # group() returns the matched text
cat
Always write patterns as raw strings using the r prefix. This stops Python from treating backslashes as escape characters.
Core Functions in the re Module
The module has a few functions you will use again and again. Learn these first.
re.match()
The re.match function checks for a match only at the start of the string. It returns a match object or None.
import re
print(re.match(r"Hello", "Hello world")) # Match at start
print(re.match(r"world", "Hello world")) # Not at start
None
Use match when the pattern must begin the string. For example, checking a fixed prefix.
re.search()
The re.search function scans the whole string and returns the first match anywhere. This is the most flexible option.
import re
result = re.search(r"\d+", "Order 42 is ready")
print(result.group()) # First number found
42
re.findall()
The re.findall function returns a list of all non-overlapping matches. This is handy for pulling many values at once.
import re
text = "Scores: 10, 25, 40"
numbers = re.findall(r"\d+", text)
print(numbers)
['10', '25', '40']
You can then convert these strings to integers. If you need the largest value, see this guide on how to find max and min in a list.
re.sub()
The re.sub function replaces matches with new text. It returns a new string.
import re
text = "Call 555-1234 now"
clean = re.sub(r"\d", "*", text) # Replace each digit
print(clean)
Call ***-**** now
Common Pattern Building Blocks
Patterns are built from small symbols. Here are the most important ones.
- \d matches a digit.
- \w matches a letter, digit, or underscore.
- \s matches whitespace.
- . matches any character except a newline.
- * means zero or more.
- + means one or more.
- ? means zero or one.
- {n} means exactly n times.
You can combine these freely. The pattern \d{3}-\d{4} matches a phone number like 555-1234.
Groups and Capturing
Parentheses create groups. Groups let you capture parts of a match and reuse them.
import re
date = "2024-05-17"
m = re.search(r"(\d{4})-(\d{2})-(\d{2})", date)
print(m.group(0)) # Whole match
print(m.group(1)) # Year
print(m.group(2)) # Month
2024-05-17
2024
05
Groups are useful when you parse structured text. They also work well with numeric input checks, like the ones in a Python leap year program with examples.
Flags for Flexible Matching
Flags change how matching works. Pass them as the last argument.
The re.IGNORECASE flag ignores letter case. The re.MULTILINE flag lets ^ and $ match each line.
import re
print(re.search(r"hello", "HELLO", re.IGNORECASE).group())
HELLO
Compiling Patterns for Speed
If you reuse a pattern many times, compile it once. This saves work on every call.
import re
pattern = re.compile(r"\d+")
print(pattern.findall("a1 b22 c333"))
['1', '22', '333']
Compiled patterns behave the same as the module functions. They are just faster in loops.
Regex in Real Programs
Regex is often used to validate input before doing math. For example, a converter that handles decimals can use a pattern to check the input first, like this Python convert Celsius to Fahrenheit example.
You can also combine regex with logic checks. A pattern like \d+ helps confirm a string is a number before you test if it is even or odd.
Common Mistakes to Avoid
Beginners often hit the same problems. Here are the big ones.
Forgetting the r prefix. Without it, "\d" may be read as an escape sequence. Always use raw strings.
Calling group() on None. If no match is found, search returns None. Calling group() then raises an error. Check for None first.
import re
m = re.search(r"cat", "dog")
if m:
print(m.group())
else:
print("No match found")
No match found
Using match when you mean search. Remember that match only checks the start of the string.
Quick Reference Table
Keep this table nearby while you practice.
- re.match checks the start only.
- re.search finds the first match anywhere.
- re.findall returns all matches as a list.
- re.sub replaces matches with new text.
- re.compile pre-builds a pattern for reuse.
Conclusion
The re module gives Python strong text-processing tools. Start with search and findall. Add groups and flags as you grow.
Practice with small patterns first. Always use raw strings. Always check for None before calling group().
With a little practice, regex becomes a fast and reliable tool in your Python toolbox.