繁体   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