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.