Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

re.Pattern.fullmatch: Match the entire string

Use this compiled regular expression method to check whether the pattern matches the entire string or the entire range selected by `pos` and `endpos`.

Version: Python 3.12

Syntax

compiled.fullmatch(string[, pos[, endpos]]) -> re.Match | None

re.Pattern.fullmatch is a method on the object returned by re.compile(). With no bounds specified, the pattern must cover the entire string. The method returns a re.Match object on success and None otherwise. A zero-length match is still a match; use result is not None to check for success.

The optional pos index sets the start (default 0), and endpos sets the exclusive end (default len(string)). The match must cover that entire range. In CPython 3.12, both indices are clamped to the interval from 0 to len(string), inclusive. There is no match if the effective endpos is less than the effective pos. If the effective bounds are equal, a zero-length match is possible. span() reports indices in the original string. Setting bounds is not the same as slicing: for example, ^ does not treat pos as a new start of the string.

Use Pattern.match() when a match at the start of the range is enough, or Pattern.search() to find a match anywhere in the range. The module-level function re.fullmatch(pattern, string, flags=0) takes the pattern as an argument but does not offer pos or endpos. The method uses the already compiled pattern and its flags; it takes no flags argument.

Examples

import re

code_pattern = re.compile(r"[A-Z]{2}-[0-9]{2}")

print(code_pattern.fullmatch("AB-42") is not None)
print(code_pattern.fullmatch("AB-42!") is not None)

match = code_pattern.fullmatch("[AB-42]", 1, 6)
assert match is not None
print(match.span())

Result

True
False
(1, 6)

The pattern requires two uppercase ASCII letters, a hyphen, and two ASCII digits. `AB-42` matches, but `AB-42!` does not. In `[AB-42]`, the range from `1` inclusive to `6` exclusive leaves out both square brackets, so `span()` returns `(1, 6)`.

Related lessons

  • Python · Lesson 29 · Intermediate · Version: 3

Sources