Python re.fullmatch
re.fullmatch tests whether a pattern matches the entire string. It returns a match object on success and None on failure.
A simple example
re.fullmatch
- Start with "12" and the pattern ^[0-9]+$
- Do this Match the whole string
- Result Match
Syntax
match = pattern.fullmatch(text)
Run this example in Python
Save the program as lesson.py. Use Python 3.9 or later.
python3 lesson.py
Validate a complete shipment identifier
A scanner imports labels written to a prescribed identifier format. Match the complete label and extract only the required fields so a valid-looking substring cannot admit a malformed shipment.
import re
pattern = re.compile(r"PK-(?P<number>[0-9]{2})")
for label in ("PK-07", "PK-07x", "PK-7"):
match = pattern.fullmatch(label)
print(match.group("number") if match else "invalid")
07 invalid invalid
A named group extracts the numeric field only after validation. The explicit digit range enforces ASCII digits, including any required leading zero.
Python documentation for re.fullmatch
Validate a sample label
A lab assistant scans a four-character sample code. The form accepts exactly two capital ASCII letters followed by two digits. Does the complete entry meet that rule?
Catch an extra digit
A clerk accidentally types one additional digit in a shelf code. The form accepts exactly two capital ASCII letters followed by two digits. Does the complete entry meet that rule?