Python Regex取代所有匹配项

时间:2017-04-21 05:28:24

标签: python regex findall

我有一个字符串,例如“嘿人#Greetings我们怎么样?#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替换当前匹配或其他方式?

2 个答案:

答案 0 :(得分:0)

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

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!

答案 1 :(得分:0)

您可以尝试这样:

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'