python re.sub group: number after \number
PythonRegexNumbersRegex GroupPython Problem Overview
How can I replace foobar
with foo123bar
?
This doesn't work:
>>> re.sub(r'(foo)', r'\1123', 'foobar')
'J3bar'
This works:
>>> re.sub(r'(foo)', r'\1hi', 'foobar')
'foohibar'
I think it's a common issue when having something like \number
. Can anyone give me a hint on how to handle this?
Python Solutions
Solution 1 - Python
The answer is:
re.sub(r'(foo)', r'\g<1>123', 'foobar')
Relevant excerpt from the docs:
> In addition to character escapes and
> backreferences as described above,
> \g