且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用带有反向引用的字符串中的 Python Match 对象

更新时间:2022-06-22 22:48:11

您可以使用 re.sub(而不是 re.match)来搜索和替换字符串.

You can use re.sub (instead of re.match) to search and replace strings.

要使用反向引用,***做法是使用原始字符串,例如:r"\1",或双转义字符串,例如"\\1":

To use back-references, the best practices is to use raw strings, e.g.: r"\1", or double-escaped string, e.g. "\\1":

import re

result = re.sub(r"ab(.*)", r"match is: \1", "abcd")
print(result)
# -> match is: cd

但是,如果您已经有一个匹配对象,可以使用expand()方法:

But, if you already have a Match Object , you can use the expand() method:

mo = re.match(r"ab(.*)", "abcd")
result = mo.expand(r"match is: \1")
print(result)
# -> match is: cd