Python re.sub group number after number
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
A classic re.sub gotcha appears when a backreference is placed next to digits in the replacement string. Python may interpret \11 as group eleven instead of group one followed by 1, which causes wrong output or group index errors. The safe fix is to use explicit group syntax with \g<1>.
Why the Ambiguity Happens
In replacement strings, backslashes introduce special patterns such as backreferences. When Python sees \1 followed immediately by a digit, it attempts to parse the longest valid group number.
Example ambiguous replacement:
Depending on groups in your pattern, this can be interpreted as group eleven or raise an error.
Use \g<n> for Unambiguous Backreferences
The recommended style is explicit braces-like group syntax.
\g<1> always means group one, and the trailing 1 is treated as literal text.
This syntax also helps with two-digit groups:
Prefer Named Groups for Readability
Named groups make replacements easier to maintain.
This is especially useful in long patterns where numeric group indexes are hard to track.
Replacement Functions Avoid Escaping Issues
For complex logic, pass a callable instead of a replacement string.
Callable replacements are clear and eliminate many backslash-related mistakes.
Raw Strings and Escape Discipline
Use raw strings for regex patterns and usually for replacement strings as well. Raw strings reduce accidental escape interpretation at Python string level.
Without raw strings, you must double-escape more sequences, which increases error risk.
Extra Edge Cases to Watch
Group zero means the entire match and can be referenced with \g<0>. This is useful when wrapping matches without rebuilding all groups.
Also avoid relying on unclear escapes in non-raw replacement strings. Write patterns and replacements consistently so future edits do not silently change behavior.
Add Small Tests for Regex Replacements
Regex replacement bugs are often subtle and data-dependent. Unit tests with representative cases provide fast protection.
These checks are inexpensive and prevent regressions during refactors.
Performance Considerations
For repeated substitutions, precompile patterns.
Compilation avoids parsing the pattern on every call and keeps code intent explicit.
Common Pitfalls
A common pitfall is using \1 directly before digits and expecting literal text after the group. Another issue is mixing normal and raw strings inconsistently, which can silently change how backslashes are processed. Developers also forget that replacement strings and regex patterns have separate escaping rules. Finally, very long numeric-group patterns become fragile over time, so named groups are usually safer and easier to review.
Summary
\1next to digits can be parsed as a larger group number.- Use
\g<1>to remove ambiguity in replacement strings. - Prefer named groups for maintainable substitutions.
- Use replacement functions for complex transformation logic.
- Combine raw strings and precompiled patterns for clearer, safer regex code.
Related reading
- Python retrieve several URLs via select.epoll
- python return, return None, and no return at all -- is there any difference?
- Python rewrite a looping numpy math function to run on GPU
- Python run non-blocking async function from sync function
- python running coverage on never ending process
- Python Scikit Random Forest Regressor Error
- Python script to copy text to clipboard
- Python service uses 100 of CPU on while loop with sleep inside docker container
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.