如何在Python中替换为正则表达式组

Pet*_*ham 7 python regex

>>> s = 'foo: "apples", bar: "oranges"'
>>> pattern = 'foo: "(.*)"'
Run Code Online (Sandbox Code Playgroud)

我希望能够像这样替换成组:

>>> re.sub(pattern, 'pears', s, group=1)
'foo: "pears", bar: "oranges"'
Run Code Online (Sandbox Code Playgroud)

有一个很好的方法来做到这一点?

Mic*_*las 10

对我来说,工作如下:

rx = re.compile(r'(foo: ")(.*?)(".*)')
s_new = rx.sub(r'\g<1>pears\g<3>', s)
print(s_new)
Run Code Online (Sandbox Code Playgroud)

注意?在re中,所以它以first结束",也在第"1组和第3组中注意,因为它们必须在输出中.

而不是\g<1>(或\g<number>)你可以只使用\1,但记得使用"原始"字符串,这种g<1>形式是优先的,因为\1可能是模棱两可的(在Python文档中查找示例).