A match object records what a Python regular expression matched. A successful `search` returns one; an unsuccessful search returns `None`. Check the result before extracting text from it. section 16.4
Named groups make parts of a match accessible:
- Name a subpattern with `(?P<name>...)`, then read its matched text with `result.group('name')`. section 16.4
- An optional group can return `None` even when the overall pattern matches. Check it before using its value as text. section 16.4
Extracting a record
For a record shaped like `surname, firstname middlename: phonenumber`, named groups can separate the names and phone number. If the middle name is absent, `result.group('middle')` is `None`; the required phone group still has matched text. section 16.4
import re
int_string = "1 2 3 4 5"
def int_match_to_float(match_obj):
return(match_obj.group('num') + ".0")
pattern = r"(?P<num>[0-9]+)"
regexp = re.compile(pattern)
regexp.sub(int_match_to_float, int_string)
'1.0 2.0 3.0 4.0 5.0'
A replacement function receives each match object from `sub`. Here it reads the named digit group and appends `.0`, turning `1 2 3 4 5` into `1.0 2.0 3.0 4.0 5.0`. section 16.5.1
Match objects can also provide more information, including substring positions; those methods are not detailed here. section 16.7

