The regex function re.sub
can be used to perform a search and replace based on regular expression matches. The repl
parameter can contain references to capturing groups used in the pattern
parameter. This can be achieved with \n
to
reference the n’th group.
When referencing a nonexistent group an error will be thrown for Python < 3.5 or replaced by an empty string for Python >= 3.5.
Noncompliant code example
re.sub(r"(a)(b)(c)", r"\1, \9, \3", "abc") # Noncompliant - result is an re.error: invalid group reference
Compliant solution
re.sub(r"(a)(b)(c)", r"\1, \2, \3", "abc")