2017-04-21 105 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

謝謝雖然問題是重新使用替換中的匹配,以便每個文本都不同。 –