Regex in Python (re)

Compiled patterns, finditer, named groups, and verbose mode.

  • python re
  • finditer
  • verbose regex
  • named groups
  • re flags

Regex in Python (re)

Compiled patterns, finditer, named groups, and verbose mode.

Commands

CommandWhat it does
re.compile with flagsCombine I, M, X at compile time
pattern.search(s)First match
pattern.finditer(s)Lazy iterator of matches
named-group replacementRefer to groups by name in sub
re.X verbose modeComments and whitespace in patterns

Example

import re
pat = re.compile(r'(?P<user>[\w.]+)@(?P<host>[\w.]+)')
print(pat.search('mail ada@ex.com').groupdict())

FAQ

search vs match vs fullmatch?

search finds anywhere, match anchors at start, fullmatch requires the whole string - pick deliberately.

How do I debug a complex pattern?

Verbose mode plus unit tests per branch; print groupdict to see captures.

SSS

search vs match vs fullmatch?
search finds anywhere, match anchors at start, fullmatch requires the whole string - pick deliberately.
How do I debug a complex pattern?
Verbose mode plus unit tests per branch; print groupdict to see captures.

Regex