Regex 'sre_constants.error: bad character range' in large regex pattern

Regex 'sre_constants.error: bad character range' in large regex pattern

错误信息如下:

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,} 可以简化为 *.