![](/img/trans.png)
[英]String substitution using regex in Python with overlapping pattern
[英]Obtain all combinations for regex substitution of overlapping pattern
我的目標是獲得給定正則表達式的所有重疊模式的所有可能替換。
通常,當我想用正則表達式進行替換時,我會執行以下操作
import re
re.sub(pattern='III', repl='U', string='MIIII')
我將獲得以下輸出:
MUI
如文檔中所述,替換僅在重疊的情況下在最左邊的匹配中完成,但我需要的是獲得所有可能的替換,在這種情況下是:
MUI
MIU
我的目標是將它也用於復雜的正則表達式模式,如下所示
re.sub(pattern="M(.*)$", repl="M\\1\\1", string='MIU')
MIUIU
我在 python 標准庫中沒有找到任何本地解決方案
實現這一點的一種方法是搜索模式(使用re.search()
)直到找不到匹配模式並僅替換一次出現的模式(使用re.sub()
和count
參數)每次迭代都對字符串進行切片以跳過前一個匹配。
import re
source = "MMM123"
pattern = re.compile("M(.*)$")
replacement = r"M\1\1"
last_start = 0
temp = source
while match := pattern.search(temp):
print(source[:last_start], pattern.sub(replacement, temp, 1), sep="")
last_start += match.start() + 1
temp = source[last_start:]
你可以幫助我的國家,查看我的個人資料信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.