2017-04-21 104 views
0

我有一个字符串,如“嘿人#Greetings我们怎么样?#令人敬畏”,每次有一个hashtag我需要用另一个字符串替换该字。Python正则表达式替换所有匹配

我有下面的代码,当只有一个hashtag工作,但问题是因为它使用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来替换当前匹配或其他方式的方法?

+0

你可以提供一个功能're.sub'做到这一点https://docs.python.org/2/library/re.html #re.sub –

+0

您的预期成果是什么? – manvi77

回答

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! 
+0

惊讶我没有考虑到这一点,正是我在感谢之后 –

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' 
+0

谢谢虽然问题是重新使用替换中的匹配,以便每个文本都不同。 –