簡體   English   中英

Python正則表達式替換所有匹配項

[英]Python Regex Replaces All Matches

我有一個字符串,例如“嗨,大家好,我們怎么樣?#Awesome”,每次有一個主題標簽時,我都需要用另一個字符串替換該單詞。

我有以下代碼,僅在使用一個#標簽時有效,但問題在於,因為它使用子替換所有實例,所以它將最后一個字符串覆蓋每個字符串。

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替換當前匹配項或另一種方法?

彼得的方法行得通。 您也可以只提供match對象作為正則表達式字符串,以便它僅替換特定的匹配項。 像這樣:

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM