python re.sub group: number after \number

拈花ヽ惹草 提交于 2019-11-26 01:37:43

问题


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?


回答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.



来源:https://stackoverflow.com/questions/5984633/python-re-sub-group-number-after-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!