我如何用foo123bar替换foobar ?

这行不通:

>>> re.sub(r'(foo)', r'\1123', 'foobar')
'J3bar'

如此:

>>> re.sub(r'(foo)', r'\1hi', 'foobar')
'foohibar'

我认为这是一个常见的问题,当有\number这样的东西。有人能给我个提示吗?


当前回答

答案是:

re.sub(r'(foo)', r'\g<1>123', 'foobar')

相关文件节选:

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.

其他回答

答案是:

re.sub(r'(foo)', r'\g<1>123', 'foobar')

相关文件节选:

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.