Python re.match vs re.search vs re.findall

Python’s re module offers multiple functions to parse and extract text using regular expressions, but each searches strings differently and returns distinct data structures. This article breaks down the practical differences between re.match(), re.search(), and re.findall(), demonstrating how they locate patterns, what they return, and how to choose the right function for your task.

re.match(): Matches from the Beginning

re.match() determines if the regular expression matches only at the very beginning of the target string. If the pattern does not match the initial character(s), the function immediately returns None, even if the pattern appears later in the string.

import re

text = "Error 404: Not Found"

# Matches because the pattern is at the start
result = re.match(r"\w+", text)
print(result.group())  # Output: Error

# Fails because digits are not at the start
result = re.match(r"\d+", text)
print(result)  # Output: None

re.search(): Finds the First Match Anywhere

re.search() scans the entire string from left to right to find the first location where the regular expression produces a match. Unlike re.match(), the match does not have to be at the beginning of the string.

import re

text = "Error 404: Not Found"

# Finds the first occurrence of digits anywhere in the text
result = re.search(r"\d+", text)
print(result.group())  # Output: 404

re.findall(): Finds All Matches

re.findall() scans the entire string and extracts all non-overlapping occurrences of the pattern. Instead of returning a Match object, it returns the matched data directly.

import re

text = "Item 1 costs $15, Item 2 costs $30, Item 3 costs $45"

# Finds all digit sequences throughout the string
result = re.findall(r"\d+", text)
print(result)  # Output: ['1', '15', '2', '30', '3', '45']

Key Differences Summary

Feature re.match() re.search() re.findall()
Search Scope Start of the string only Entire string (stops at first match) Entire string
Number of Matches 1 (if at start) 1 (first occurrence) All occurrences
Return Type Match object or None Match object or None list of strings/tuples (or empty list)
Accessing Text Requires .group() Requires .group() Elements accessed directly via list indexing