>>> s = 'foo: "apples", bar: "oranges"'
>>> pattern = 'foo: "(.*)"'
我希望能够代入这样的组:
>>> re.sub(pattern, 'pears', s, group=1)
'foo: "pears", bar: "oranges"'
有什么好的方法吗?
最佳答案
对我来说是这样的:
rx = re.compile(r'(foo: ")(.*?)(".*)')
s_new = rx.sub(r'\g<1>pears\g<3>', s)
print(s_new)
公告?
在 re 中,所以它以第一个 "
结尾, 另请注意 "
在第 1 组和第 3 组中,因为它们必须在输出中。
而不是 \g<1>
(或 \g<number>
)你可以只使用 \1
,但请记住使用“原始”字符串和 g<1>
表格是首选,因为 \1
可能不明确(在 Python doc 中查找示例)。
关于python - 如何代入 Python 中的正则表达式组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3059151/