python re.sub group: number after number

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 will use the substring
matched by the group named name, as
defined by the (?P…) syntax.
g uses the corresponding
group number; g<2> is therefore
equivalent to 2, but isn’t ambiguous
in a replacement such as g<2>0. 20
would be interpreted as a reference to
group 20, not a reference to group 2
followed by the literal character ‘0’.
The backreference g<0> substitutes in
the entire substring matched by the
RE.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x