我正在尝试为我们已经拥有的聊天服务添加一个更高效的骂人过滤器,但似乎无法让我的正则表达式在我的实时django服务器上工作。
我在Python 2.6.7上运行最新的稳定版Django。
下面是我的代码:
def replacement(match):
    return "*" * len(match.group(0))
def censored_string(cFilter, dirty):
    clean = str(dirty)
    wordList = cFilter.mutations.split(',')
    wordList.sort(key = len)
    wordList.reverse()
    for swear_word in wordList:
        target_word = swear_word.strip()
        result = re.sub("(?i)\\b(("+target_word+"){1,})(s{0,1})\\b",replacement, clean)
        clean = result
    return clean为了记录-这工作使用我的本地服务器设置,我可以确认也是使用python 2.6.7和相同的django版本,但是我没有做太多的django或python,因为大约10个月前和最近继承了这个服务器设置-如果我遗漏了什么,请让我知道。
错误的输出如下:
{
    "error_message": "multiple repeat",
    "traceback": ... "result = re.sub(\"(?i)\\\\b(\"+target_word+\"){1,}(s{0,1})\\\\b\",censored_word(target_word), clean)\n\n  File \"/usr/lib/python2.6/re.py\", line 151, in sub\n    return _compile(pattern, 0).sub(repl, string, count)\n\n  File \"/usr/lib/python2.6/re.py\", line 245, in _compile\n    raise error, v # invalid expression\n\nerror: multiple repeat\n"
}我已经尝试过使用和不使用贪婪等等,但现在迷路了-任何意见都将不胜感激
干杯,
迈克尔
发布于 2012-05-03 17:03:07
我不认为问题出在正则表达式上,而是在你的单词列表上。该列表很可能包含被解释为regex特殊字符的字符。这对我来说很有效:
#!/usr/bin/python
import re
def replacement(match):
    return "*" * len(match.group(0))
def censored_string(dirty):
    clean = str(dirty)
    wordList = ["fuck", "shit", "damn"]
    for swear_word in wordList:
        target_word = swear_word.strip()
        result = re.sub("(?i)\\b(("+target_word+"){1,})(s{0,1})\\b",replacement, clean)
        clean = result
    return clean
print censored_string("god damn i love bananas and fucking fuckfuck shits")
# god **** i love bananas and fucking ******** *****发布于 2012-05-11 02:23:42
从字面上看,来自re的“多个重复”错误意味着在您的模式中有多个重复指令应用于相同的表达式。
重复指令可以是*、+、?、{m}、{m,n}等。如果将这些指令中的多个应用于一个模式,您将收到该错误。同样,target_word很可能包含您可能忘记转义的正则表达式特殊字符。使用re.escape()就可以做到这一点,并再给它一次机会。
也就是说。
result = re.sub("(?i)\\b((" + re.escape(target_word) + "){1,})(s{0,1})\\b", replacement, clean)发布于 2017-10-27 16:21:22
有人好心地推荐了Devy上面的答案。
我自己的用例也与"re“和"Django”一起使用。
我得到了错误--“位置12的多个重复”,我的初始代码如下--
str_7 = re.findall(r'([\d+]{1,20}[A-Z])',str_7)
## multiple repeat at position 12#上述错误-> (r'(\d+{1,20} --不能同时包含"\d+“和{1,20}。
此外,其他地方建议的re.escape也不是理想的解决方案-尽量不要有多个-“重复指令”
因此,和我的例子一样,“加号运算符”或“正闭包”后面不应该跟“花括号运算符”{m,n}
https://stackoverflow.com/questions/10427839
复制相似问题