re — regular expressions

Python re.search, re.match, re.fullmatch, re.findall, and re.sub, including the difference between searching and matching.

re is a standard-library module for regular expressions. It is not a parser for HTML, JSON, or nested grammars, and it is not a third-party package such as regex.

Write patterns as raw strings, for example r"\d+", so that backslashes stay visible to the regex engine. The functions below all accept a pattern and an optional flags argument.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

search, match, and fullmatch

search() looks for the first match anywhere in the string. match() checks only at the beginning. fullmatch() requires the pattern to cover the entire string. All three return a match object, or None when there is no match.

findall and sub

findall() returns all non-overlapping matches as a list of strings, or a list of tuples when the pattern contains groups. finditer() yields match objects instead. sub() returns a new string with replacements, leaving the original string unchanged.

re.findall and re.sub

re.findall(pattern, string, flags=0)
re.sub(pattern, repl, string, count=0, flags=0)

Collect every match, or replace matches with a string or a function.

ParameterDescription
replA replacement string or a function that receives a match object and returns a string.
countMaximum number of replacements. 0 means replace all.
flagsOptional modifiers such as re.IGNORECASE or re.MULTILINE. Combine flags with the bitwise OR operator.

Returns: findall() returns a list. sub() returns the replaced string.

  • Word characters in \w include letters, digits, and the underscore. A hyphen is not a word character, so r"\w+" splits "one-two" into two matches.
  • Greedy quantifiers such as .* consume as much as possible. Use .*? when you need the shortest match.
python
import re

print(re.findall(r"\w+", "one-two three"))
print(re.sub(r"\s+", ",", "a   b\tc"))
print(re.sub(r"\d+", "N", "port 80 and 443", count=1))

Expected output

['one', 'two', 'three']
a,b,c
port N and 443

Official documentation →