Python 正则表达式替换所有匹配项

Python Regex Replaces All Matches

我有一个字符串,例如 "Hey people #Greetings how are we? #Awesome",每次有一个主题标签时,我都需要用另一个字符串替换该词。

我有以下代码,它在只有一个主题标签时有效,但问题是因为它使用 sub 替换所有实例,所以它会用最后一个字符串覆盖每个字符串。

match = re.findall(tagRE, content)
print(match)
for matches in match:
    print(matches)
    newCode = "The result is: " + matches + " is it correct?"
    match = re.sub(tagRE, newCode, content)

我应该怎么做才能替换当前匹配项?有没有办法使用 re.finditer 来替换当前匹配或其他方式?

彼得的方法行得通。您也可以只提供匹配对象作为正则表达式字符串,以便它只替换该特定匹配项。像这样:

newCode = "whatever" + matches + "whatever"
content = re.sub(matches, newCode, content)

我 运行 一些示例代码,这是输出。

import re

content = "This is a #wonderful experiment. It's #awesome!"
matches = re.findall('#\w+', content)
print(matches)
for match in matches:
    newCode = match[1:]
    print(content)
    content = re.sub(match, newCode, content)
    print(content)

#['#wonderful', '#awesome']
#This is a #wonderful experiment. It's #awesome!
#This is a wonderful experiment. It's #awesome!
#This is a wonderful experiment. It's #awesome!
#This is a wonderful experiment. It's awesome!

你可以这样试试:

In [1]: import re

In [2]: s = "Hey people #Greetings how are we? #Awesome"
In [3]: re.sub(r'(?:^|\s)(\#\w+)', ' replace_with_new_string', s)
Out[3]: 'Hey people replace_with_new_string how are we? replace_with_new_string'