Python

Python Regular Expressions — re, search, match, Groups, and Substitution

A regular expression describes a shape of text: a run of digits, a date, a word standing alone. The re module searches a string for that shape, pulls out the parts you mark, and can replace or split on what it finds. This guide shows the working core: a first search and its match object, the difference between search, match, and fullmatch, numbered and named groups, collecting every match, replacing and splitting, greedy and lazy quantifiers, and compiled patterns with literal escaping.

Written November 12, 2026 · Tested with Python 3.12.3 · 10 min read

By the end of this guide
  • The main program: search returns a match or None
  • match starts at the beginning, fullmatch must cover all of it
  • Groups capture parts of a match
  • findall collects, finditer reports positions

Written November 12, 2026

Tested with Python 3.12.3

What this guide is

A regular expression is a pattern written in a small language of its own. Some characters stand for themselves, and some stand for a kind of character or a count: \d means one digit, + after a part means one or more of it, and square brackets name a set to pick from. The re module matches that pattern against a string. Patterns are usually written as raw strings, with an r in front of the quote, so backslashes reach the pattern as written instead of starting a string escape first.

The main program: search returns a match or None

The search function scans the whole string and returns a match object for the first place the pattern fits. The match reports the text it found and where it sits:

Python
import re

text = "order 4821 shipped on 2026-11-12"
m = re.search(r"\d+", text)
print(m.group())
print(m.span())
print(text[m.start():m.end()])
missing = re.search(r"\d+", "no digits here")
print(missing)

The exact output:

Output
4821
(6, 10)
4821
None

The pattern \d+ means one or more digits, so the first fit is the order number. The span is the pair of indexes where the match starts and ends, and slicing the string with the start and end indexes gives the same text back. A search that finds nothing returns None rather than raising an error, so code that uses the match first checks whether the search found anything at all.

match starts at the beginning, fullmatch must cover all of it

Three search functions differ only in where the pattern may fit. The match function tries only at the start of the string. The search function tries at every position. The fullmatch function requires the pattern to cover the string from end to end:

Python
import re

text = "abc123"
print(re.match(r"[a-z]+", text).group())
print(re.match(r"\d+", text))
print(re.search(r"\d+", text).group())
print(re.fullmatch(r"[a-z]+\d+", text).group())
print(re.fullmatch(r"[a-z]+", text))

The exact output:

Output
abc
None
123
abc123
None

The bracket part [a-z]+ means one or more lowercase letters, so it matches at the start, while the digit pattern fails there because the string does not begin with a digit. The same digit pattern succeeds under search, which is free to start later in the string. Fullmatch is the strict one: letters followed by digits covers the whole string, but letters alone leave the digits uncovered, so that call returns None. Picking between the three is picking how much of the string the pattern has to account for.

Groups capture parts of a match

Round brackets in a pattern do two jobs at once: they group a part of the pattern, and they capture the text that part matched. Captures come back by number, counting from the left, and group zero is always the whole match:

Python
import re

m = re.search(r"(\d{4})-(\d{2})-(\d{2})", "due 2026-11-12 today")
print(m.group(0))
print(m.group(1), m.group(2), m.group(3))
print(m.groups())
named = re.search(r"(?P<year>\d{4})-(?P<month>\d{2})", "due 2026-11-12")
print(named.group("year"), named.groupdict())

The exact output:

Output
2026-11-12
2026 11 12
('2026', '11', '12')
2026 {'year': '2026', 'month': '11'}

The {4} and {2} parts fix an exact count, so the date pattern reads as four digits, a dash, two digits, a dash, two digits. The groups call returns every capture as one tuple. A group can also carry a name, written (?P...) in the pattern, and a named group reads back by that name or as part of the groupdict dictionary. Names pay off when a pattern grows: a reader can tell what the year capture is without counting brackets.

findall collects, finditer reports positions

When a string holds many matches, findall returns them all as a list of strings. If the pattern has groups, each entry becomes a tuple of the captures instead. The finditer function yields match objects one by one, which is the form to use when the positions matter:

Python
import re

text = "a1 b22 c333"
print(re.findall(r"\d+", text))
print(re.findall(r"([a-z])(\d+)", text))
print(re.findall(r"z+", text))
for m in re.finditer(r"\d+", text):
    print(m.group(), m.span())

The exact output:

Output
['1', '22', '333']
[('a', '1'), ('b', '22'), ('c', '333')]
[]
1 (1, 2)
22 (4, 6)
333 (8, 11)

A pattern with no match gives an empty list, never None, so findall results can go straight into a loop or a length check. The change of return shape when groups appear surprises many first users: the list stops holding whole matches and holds the captures instead. When a program needs both the text and the place for each match, finditer is the direct route, since each match object carries its own span.

sub replaces matches, split cuts on them

The sub function returns a new string with each match replaced. Its subn twin also reports how many replacements it made. The split function cuts a string wherever the pattern matches and returns the pieces:

Python
import re

text = "one  two\tthree"
print(re.sub(r"\s+", "-", text))
print(re.subn(r"\s+", "-", text))
print(re.split(r"\s+", text))
print(re.sub(r"\d", "#", "a1b2c3", count=2))

The exact output:

Output
one-two-three
('one-two-three', 2)
['one', 'two', 'three']
a#b#c3

The \s part matches any whitespace character, so the pattern \s+ covers the double space and the tab as one run each, which is why the count is two and not three. That one pattern handles the spacing a hand-written split on a single space character would miss. The count argument caps how many matches get replaced, counting from the left; the third digit in the last line keeps its place because the cap ran out.

Greedy takes the most, lazy takes the least

A quantifier such as * or + is greedy by default: it takes as much text as it can while still letting the rest of the pattern match. Adding a question mark after the quantifier makes it lazy, so it takes as little as it can:

Python
import re

html = "<b>one</b><b>two</b>"
print(re.search(r"<b>.*</b>", html).group())
print(re.search(r"<b>.*?</b>", html).group())
print(re.findall(r"[aeiou]", "regular"))
print(re.findall(r"[^0-9]+", "ab12cd"))

The exact output:

Output
<b>one</b><b>two</b>
<b>one</b>
['e', 'u', 'a']
['ab', 'cd']

The dot matches any character except a newline, so the greedy form runs from the first opening tag to the last closing tag and swallows both elements as one match. The lazy form stops at the first closing tag that completes the pattern. A leading caret inside brackets negates the set: [^0-9] means any character that is not a digit, so the last line collects the letter runs and skips the digits between them. When a match comes back longer than expected, a greedy quantifier in the middle is the first suspect.

Compiled patterns, flags, and literal text

A pattern used more than once can be compiled a single time with re.compile, which returns a pattern object whose methods mirror the module functions. Flags given at compile time, such as re.IGNORECASE, change how the pattern matches. And when the text to find is data rather than a pattern, re.escape turns it into a pattern that matches it literally:

Python
import re

pattern = re.compile(r"python", re.IGNORECASE)
print(pattern.findall("Python python PYTHON"))
print(re.escape("a+b (test)"))
print(re.search(re.escape("a+b"), "use a+b here").group())
print(bool(re.search(r"\bcat\b", "the cat sat")))
print(bool(re.search(r"\bcat\b", "concatenate")))

The exact output:

Output
['Python', 'python', 'PYTHON']
a\+b\ \(test\)
a+b
True
False

Without escaping, the plus in a+b would mean one or more of the letter a, and the search would look for the wrong text entirely. The escape call puts a backslash in front of each character that carries a special meaning, so the pattern matches the literal string. The \b part is a word boundary, the empty place between a word character and a non-word character, so the last two lines show the pattern finding cat as a whole word and refusing it inside a longer word.

Which function for which job

Job Function Why
Find the first fit anywhere in a string re.search Scans every position and returns a match or None
Require the fit to start the string re.match Anchored at the start, free at the end
Require the pattern to cover the whole string re.fullmatch Both ends anchored; anything uncovered returns None
Pull marked parts out of one match Groups on the match object group by number or name, groups for all captures at once
Collect every fit as plain data re.findall A list of strings, or of capture tuples when groups exist
Walk fits with their positions re.finditer Yields match objects, each with its own span
Replace or cut on fits re.sub, re.split One returns a rebuilt string, the other the pieces between fits
Reuse one pattern, or match letter case loosely re.compile with flags The pattern and its flags travel together as one object
Search for text that is data, not a pattern re.escape first Special characters lose their pattern meaning

Checklist

  • Before using a match, check it is not None; a failed search returns None instead of raising.
  • Before picking a search function, decide how much of the string the pattern must cover: anywhere, the start, or all of it.
  • Before reading findall results, check whether the pattern has groups; groups change each entry from a string to a tuple.
  • Before trusting a long match, check for a greedy quantifier in the middle; the lazy form with a trailing question mark takes the least text instead.
  • Before searching for text that came from data or a user, pass it through re.escape so its special characters match literally.
  • Before writing a pattern without the raw-string prefix, count its backslashes; the r prefix keeps the pattern as written.

Sources

Keep Exploring