search, match and fullmatch

re · Essentials · 8 min

Picking the right function is the difference between a working validator and one that accepts garbage.

A regular expression is a small pattern language for text. The three basic functions differ only in where the pattern must match:

  • re.search(pattern, text) finds the first match anywhere in the text.
  • re.match(pattern, text) only matches at the start of the text.
  • re.fullmatch(pattern, text) requires the pattern to match the entire text. Use it for validation.

Each returns a Match object on success or None on failure, so the usual idiom is:

if m := re.search(r"\d+", text):
    print(m.group())

m.group() (or m[0]) is the matched text, and m.start(), m.end() and m.span() give its position.

Write patterns as raw strings: r"\d+". In a normal string literal, Python processes backslashes first, so "\b" would be a backspace character instead of the regex word boundary. Raw strings pass backslashes through to the regex engine untouched.

Plain characters match themselves; the special characters . ^ $ * + ? { } [ ] \ | ( ) have meanings covered in the next lessons. Many tasks don't need regex at all: "abc" in text, text.startswith(...) and str.split are simpler and faster for fixed strings.

Example

import re

text = "Order 1234 shipped on 2025-03-01"

m = re.search(r"\d+", text)
print(m.group(), m.span())               # 1234 (6, 10)
print(re.match(r"\d+", text))            # None: text starts with 'O'
print(re.match(r"Order", text) is not None)   # True

for candidate in ["2025", "2025a", "x2025"]:
    print(candidate, bool(re.fullmatch(r"\d{4}", candidate)))
# 2025 True
# 2025a False
# x2025 False

print("\b" == "\x08", r"\b" == "\\b")   # True True

Remember

  • search anywhere, match at the start, fullmatch the whole string
  • They return a Match object or None; test the result before using it
  • Always write patterns as raw strings: r'...'

Watch out for

  • Using re.match for validation; it accepts any string that merely begins with a valid value.

Check yourself

  1. Which call returns a match for the text 'id: 42'?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/library/re.html#re.search

Builds on

Nothing: this is a foundation.

Unlocks