Python regex subsitution: separate backreference from digit

无人久伴 提交于 2019-12-01 02:28:59

You can use \g<1>, as mentioned in the docs.

Instead of using a backreference with a sequence number (\1), you can use named groups and the problem is solved:

# replace all twin digits by zeroes, but retain whitespace in between
re.sub(r"\d(?P<whitespace>\s*)\d", r"0\g<whitespace>0", "0 1")
>>> '0 0'

Turns out this trick is in fact described in the documentation of re.sub.

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