Substitution — the other half of regex
re.sub(pattern, replacement, text) replaces every non-overlapping match of pattern with replacement.
The replacement can be:
- A literal string:
re.sub(r'\d+', 'NUM', 'a 1 b 22 c 333')→'a NUM b NUM c NUM' - A pattern with backreferences:
r'\1'for group 1,r'\g<name>'for named groups,r'\g<0>'for whole match. - A callable: receives a Match object, returns a string. Most powerful for dynamic logic.
The count parameter
re.sub(pattern, replacement, text, count=N) replaces only the first N matches. Useful for "only fix the first occurrence" or "don't process more than X."
re.subn — get the count back
re.subn returns a tuple (new_string, num_replacements). Useful when you need to know whether anything changed.
re.split — split with a regex separator
re.split(pattern, text) is like str.split but the separator can be any regex. Splits on every match.
If the pattern contains capture groups, the captured text is INCLUDED in the result list. re.split(r'(\W+)', 'hello, world') returns ['hello', ', ', 'world'] — the separator is preserved.