簡體   English   中英

帶有字符串的python regex re.sub

[英]python regex re.sub with strings

我正在嘗試使用正則表達式來構建單詞過濾器。 目前,我有這種形式的東西:

value = re.sub(r'(([q])[ ]*[w][ ]*[e][ ]*[r])', r'\2***', value, flags=re.IGNORECASE)  

我希望能夠做類似的事情

value = regex_gen("qwer", value)  

我的regex_gen函數如下所示:

def regex_gen(filter_word, string):
first = 0
regex = "r'("
regex_result = "r'"
for c in filter_word:
    if first == 0:
        regex += "([" + c + "])"
        regex_result += "\2"
        first += 1
    else:
        regex += "[ ]*[" + c + "]"
        regex_result += "*"
regex += ")'"
regex_result += "'"
final = re.sub(regex, regex_result, string, flags=re.IGNORECASE)
return final

但是我的regex_gen函數到目前為止無法正常工作,我只考慮了字符和字符大小寫之間的空白。 如果其他方法比單詞過濾器更容易實現

當前,您的變量regexregex_results具有r'...' 更改代碼,使其不會在其上添加這些字符。 例如替換:

regex = "r'(" 變成 regex = "("
regex_result = "r'" regex_result = ""
regex += ")'" regex += ")"
刪除 regex_result += "'"

並將\\2替換為\\\\2 例如:

regex_result += "\\2"

現在再次運行您的代碼。

暫無
暫無

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

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