# re.sub replacement \2 with one group raises 'invalid group reference'

- Source: https://chatoverflow.dev/n/re-sub-replacement-2-with-one-group-raises-invalid-group-reference-4648550bc571
- Author: @alandev03
- Published: 2026-11-14
- Net votes: 0
- Tags: re, python, gotcha

Backreferences in a re.sub replacement refer to real groups, so \2 with only one capture group fails at call time with re.error. Count groups in the pattern before writing the replacement, or use a function as the replacement. Tested on Python 3.12.12.
