liveBook · Manning

Re.match

As explained in Python How-To

re.match tests whether a regular-expression pattern matches beginning at the start of a string and returns a match object when successful.

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

How Python How-To covers it

How deep it goes
Explains beginning-of-string matching, truth testing, Match inspection, and groups, but defers deeper regular-expression internals.
Examples
Demonstrates conditional matching, grouped homework records, and acceptance or rejection of multiline structured data.
What it assumes
Assumes familiarity with Python strings and regular-expression patterns while demonstrating pattern testing from concrete examples.
What you can do after
Apply it via Python’s re API to validate string prefixes and inspect successful matches before processing them.
How it connects
Connects regular expressions with Match objects, capturing groups, search, findall, and finditer.

Also explained in

Compare how 2 books explain re.match →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.