python - 大型正则表达式模式中的正则表达式 'sre_constants.error: bad character range'

标签 python regex python-2.7

以下是错误信息:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/re.py", line 194, in compile
    return _compile(pattern, flags)
  File "/usr/lib/python2.7/re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: bad character range
这是我的对象:
>>> re101121=re.compile("""(?i)激[ _]{0,}活[ _]{0,}邮[ _]{0,}箱|(click|clicking)[ _]{1,}[here ]{0,1}to[ _]{1,}verify|stop[ _]{1,}mail[ _]{1,}.{1,16}[ _]{1,}here|(click|clicking|view|update)([ _-]{1,}|\\xc2\\xa0)(on|here|Validate)[^a-z0-9]{1}|(點|点)[ _]{0,}(擊|击)[ _]{0,}(這|这|以)[ _]{0,}(裡|里|下)|DHL[ _]{1,}international|DHL[ _]{1,}Customer[ _]{1,}Service|Online[ _]{1,}Banking|更[ _]{0,}新[ _]{0,}您[ _]{0,}的[ _]{0,}(帐|账)[ _]{0,}户|CONFIRM[ _]{1,}ACCOUNT[ _]{1,}NOW|avoid[ _]{1,}Account[ _]{1,}malfunction|confirm[ _]{1,}this[ _]{1,}request|verify your account IP|Continue to Account security|继[\\s-_]*续[\\s-_]*使[\\s-_]*用|崩[\\s-_]*溃[\\s-_]*信[\\s-_]*息|shipment[\\s]+confirmation|will be shutdown in [0-9]{0,} (hours|days)|DHL Account|保[ ]{0,}留[ ]{0,}密[ ]{0,}码|(Password|password|PASSWORD).*(expired|expiring)|login.*email.*password.*confirm|[0-9]{0,} messages were quarantined|由于.*错误(的)?(送货)?信息|confirm.*(same)? password|keep.*account secure|settings below|loss.*(email|messages)|simply login|quick verification now""")

最佳答案

最小化后,您的错误归结为 re.compile("""[\\s-_]""") .这确实是一个糟糕的字符范围;你可能是说破折号是字面意思 re.compile(r"[\s\-_]") (始终将原始字符串用于正则表达式 r"..." )。将破折号移到括号组的末尾也有效:r"[\s_-]" .
以后,尽量binary search找到最小的失败输入:删除正则表达式的右半部分。如果仍然失败,则问题一定出在左半部分。删除剩余子字符串的右半部分并重复,直到您减少到最小的失败案例。当问题跨越两半时,这种技术并不总是有效,但尝试一下也无妨。
正如评论中提到的,拥有如此庞大的正则表达式非常奇怪,但我假设您知道自己在做什么。
另外,这个正则表达式中有一些反模式(请原谅双关语),如 {0,}可以简化为 * .

关于python - 大型正则表达式模式中的正则表达式 'sre_constants.error: bad character range',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67206125/

相关文章:

python - 如何在不刷新 Flask 项目页面的情况下更新值?

python - Print 不使用临时 __str__() 或 __repr__() 方法

python - 如何从python列表的每个元素中删除前缀?

python - 当指定面色时,边缘线在 mplot3d 冲浪中消失

python - Cython:控制cythonize停止将编译后的 `.c`文件从 `.pyx`文件放入安装目录

python - 我想找到线程消息并使用 slack-api 删除它

python - Tinyurl 自定义别名的语法?

c# - 解析测量单位

python Regex-根据条件获取匹配

python - 将值附加到 python 中元组的列表