Extract Fields with Capturing and Named Groups
Core idea
Parentheses capture matched substrings; group(0) is the entire match, and group(1) is the first capture. The syntax (?P<name>...) assigns a name to a capture. Use (?:...) to group alternatives or repetitions without creating a capture.
import rem = re.fullmatch(r"(?P<zone>[A-Z]+):(?P<count>[0-9]+)", "WEST:12")if m: print(m.group("zone"), int(m.group("count")))Named groups let you access fields without remembering their numeric position. int converts the digit text into a number.
Inspect an optional group
import rem = re.fullmatch(r"([A-Z]+)(?:-([0-9]+))?", "BOX")print(m.group(1), m.group(2))print(m.group(0))The optional numeric group did not participate, so its value is None. The outer noncapturing group does not get a number.
Common mistake
A successful match does not imply every optional group participated. Check None before converting a captured field.
Practice
Extract a zone and integer count from a string like "WEST:12"; return a clear fallback for malformed input.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Capturing groups
Check your understanding of capturing and named groups.
What is printed?
import rem=re.fullmatch(r"(?P<x>[A-Z]+)-(?P<y>[0-9]+)","AB-42")print(m.group("x"),m.group("y"))What is printed?
import reprint(re.fullmatch(r"A(B)?","A").group(1))Which syntax groups without capturing?
What does group(0) return?