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

7 投票
2 回答
7941 浏览
提问于 2025-04-16 00:05
>>> s = 'foo: "apples", bar: "oranges"'
>>> pattern = 'foo: "(.*)"'

我想要能够像这样替换到这个组里面:

>>> re.sub(pattern, 'pears', s, group=1)
'foo: "pears", bar: "oranges"'

有没有什么好的方法可以做到这一点呢?

2 个回答

0
re.sub(r'(?<=foo: ")[^"]+(?=")', 'pears', s)

这个正则表达式用来匹配一串字符,具体要求如下:

  • 必须跟在字符串 foo: " 后面,
  • 不能包含双引号,
  • 并且后面要跟一个 "

(?<=)(?=) 是用来做 前瞻和后顾的。

如果 foo 的值里面有转义的引号,这个正则表达式就会失效。可以使用下面这个正则表达式来同时匹配这些情况:

re.sub(r'(?<=foo: ")(\\"|[^"])+(?=")', 'pears', s)

示例代码

>>> s = 'foo: "apples \\\"and\\\" more apples", bar: "oranges"'
>>> print s
foo: "apples \"and\" more apples", bar: "oranges"
>>> print   re.sub(r'(?<=foo: ")(\\"|[^"])+(?=")', 'pears', s)
foo: "pears", bar: "oranges"
10

对我来说,下面的代码可以这样使用:

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

注意到正则表达式中的 ?,它表示匹配到第一个 " 就结束了。同时,注意第1组和第3组中的 ",因为它们必须出现在输出结果中。

你可以用 \1 来代替 \g<1>(或者 \g<number>),但要记得使用“原始”字符串。而且 g<1> 的形式更受欢迎,因为 \1 可能会引起歧义(可以在 Python文档 中查看示例)。

撰写回答