Codectionary / Developer documentation / Python

Regex Validation and Named Groups

re.fullmatch requires the entire input to satisfy a pattern. Named capture groups extract validated components without fragile numeric group positions. Run as a Python 3.11+ script.

Syntax

re.fullmatch(r"pattern", text); match.group("name")

Examples

Regex Validation and Named Groups

Run as a Python 3.11+ script.

import re
pattern = re.compile(r"(?P<kind>[A-Z]+)-(?P<number>[0-9]{3})")
match = pattern.fullmatch("TASK-042")
if match:
    print(match.group("kind"), int(match.group("number")))
print(pattern.fullmatch("TASK-042-extra") is None)
  1. Expected output: TASK 42 True
  2. The named groups isolate the prefix and digits. fullmatch rejects trailing text that a prefix match would accept.

Best practices

  • Use raw string literals for regex patterns.
  • Keep patterns bounded and simple when processing untrusted input; use a parser for nested grammar.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading