The four functions you'll use 90% of the time
Python's built-in regex lives in the re module. Four functions cover most use cases:
re.search(pattern, text)— find the first match anywhere in text. Returns a Match object or None.re.match(pattern, text)— match at the START of text only. Returns Match or None.re.fullmatch(pattern, text)— match the ENTIRE text. Returns Match or None.re.findall(pattern, text)— return all non-overlapping matches as a list.re.finditer(pattern, text)— return an iterator of Match objects (preferred over findall when you have groups).
The Match object
When a pattern matches, you get a Match object with these key methods:
m.group()orm.group(0)— the entire matchm.group(N)— the Nth capture groupm.group('name')— a named capture groupm.groups()— tuple of all numbered groupsm.groupdict()— dict of all named groupsm.start(),m.end(),m.span()— match position
Match vs search — the most common confusion
re.match only checks the start of the string. re.match(r'world', 'hello world') returns None. Use re.search for "contains." Use re.match for "starts with." Use re.fullmatch for "is exactly."