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
| Command | What it does |
|---|---|
re.compile with flags | Combine I, M, X at compile time |
pattern.search(s) | First match |
pattern.finditer(s) | Lazy iterator of matches |
named-group replacement | Refer to groups by name in sub |
re.X verbose mode | Comments 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.
Soalan Lazim
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.