Use re.match when a regular-expression pattern must match at the beginning of a string. A successful call returns a Match object; otherwise it returns None. section 2.4.4 section 2.4.5
Check a record prefix
match = re.match("pattern", "string to match") if match: print("do something with the matched") else: print("found no matches") Use the Match object directly in the condition: successful matches evaluate to True. section 2.4.4
Choose re.match according to where the pattern is allowed to occur:
- Use re.match when the match must begin at position zero; use re.search when a match anywhere in the string is valid. section 2.4.4 section 2.4.5
- Use match.group(), span(), start(), and end() to inspect the matched text and its location. section 2.4.4
- Use capturing groups when a valid prefix contains separate fields, then retrieve all groups or selected group numbers. section 2.4.4
Validate structured lines
regex = re.compile(r"(\d{3}), (\w+); (.+)") for line in text_data.split("\n"): match = regex.match(line) if match: print(f"Matched: {match.group()}") else: print(f"No Match: {line}") This accepts lines beginning with three digits, a comma, a word, a semicolon, and trailing text; malformed records are rejected. section 2.5.1
match = re.match(r"(\w+), (\w+)", "Homework, urgent; today")
print(match)
# output: <re.Match object; span=(0, 16), match='Homework, urgent'>
match.groups()
# output: ('Homework', 'urgent')
match.group(0)
# output: 'Homework, urgent'
match.group(1)
# output: 'Homework'
match.group(2)
# output: 'urgent'
Inspect a successful beginning-of-string match and retrieve the complete match alongside its captured groups. section 2.4.4

