假設有一個字串
"An example striiiiiing with other words"
我需要'i'用'*'s替換s 'str******ng'。的數量'*'必須與 相同'i'。僅當連續'i'大于或等于 3時才應進行此替換。如果數量'i'小于 3,則有不同的規則。我可以硬編碼:
import re
text = "An example striiiiing with other words"
out_put = re.sub(re.compile(r'i{3}', re.I), r'*'*3, text)
print(out_put)
# An example str***iing with other words
但是 i 的數量可以是大于 3 的任何數字。我們如何使用正則運算式做到這一點?
uj5u.com熱心網友回復:
該i{3}模式的匹配iii字串中的任何地方。您需要i{3,}匹配三個或更多is。但是,要使其全部作業,您需要將您的匹配項傳遞到用作替換引數的可呼叫物件中re.sub,您可以在其中獲取匹配文本長度并正確相乘。
此外,建議在 之外宣告正則運算式re.sub,或者只使用字串模式,因為模式已被快取。
這是解決問題的代碼:
import re
text = "An example striiiiing with other words"
rx = re.compile(r'i{3,}', re.I)
out_put = rx.sub(lambda x: r'*'*len(x.group()), text)
print(out_put)
# => An example str*****ng with other words
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/315085.html
