为什么将(。| \ n)*更改为(。|)*会导致性能大幅下降?

时间:2018-10-31 13:59:45

标签: python regex performance backtracking

我正在编写正则表达式以警告我收到华为CPE时的警告。我必须匹配的文本是:

Warning: There are security risks in the configuration file. You are advised to save the configuration immediately. If you choose to save, the current configuration file will be unavailable after version downgrade.Are you sure to save now? [Y/N]:

我用来匹配它的正则表达式如下:

Warning:(.|\n)*Are you sure to continue\?\s*\[Y/N\]:\s*$

运行正常:

$ python3 -m timeit -s "import re;T=$text" "re.search(r'Warning:(.|\n)*Are you sure to continue\?\s*\[Y/N\]:\s*$', T)"
100000 loops, best of 3: 9.8 usec per loop

如果我将\n更改为包含空格的任何内容,则正则表达式会突然变得异常缓慢:


Warning:(.| )*Are you sure to continue\?\s*\[Y/N\]:\s*$

尝试使用\n|\s,并且执行相同的操作

我不担心timeit仅仅是因为它已经在我的repl上运行了几分钟。

这可能是灾难性回溯的问题,但是我想了解为什么会发生。特别是:为什么空白很重要?

每个空格已被.匹配,因此它根本不能被使用,如果.不匹配,那么也将不匹配,因此我不明白为什么这会增加回溯步骤的数量。

0 个答案:

没有答案