编程语言
首页 > 编程语言> > python – 了解是什么让这个正则表达式变得如此缓慢

python – 了解是什么让这个正则表达式变得如此缓慢

作者:互联网

我有一个正则表达式:

import re

regexp = re.compile(r'^(?P<parts>(?:[\w-]+/?)+)/$')

它匹配一个像foo / bar / baz /这样的字符串,并将foo / bar / baz放在一个名为parts的组中(/?与/ $support this相结合).

这非常合适,直到匹配不以斜线结尾的字符串.然后,它会以看似指数的速度变慢,每个新的字符都会添加到您匹配的字符串中.

# This is instant (trailing slash)
regexp.match('this-will-take-no-time-at-all/')

# This is slow
regexp.match('this-takes-about-5-seconds')

# This will not finish
regexp.match('this-probably-will-not-finish-until-the-day-star-turns-black')

我试图理解为什么这个特定的递归问题只发生在/ $(尾部斜杠)不在字符串中时(即不匹配).你能帮我理解尾随斜杠和非尾随斜线情况下底层算法的控制流吗?

注意

我不是在寻找我想要的模式的解决方案.我试图了解具体的正则表达式.

解决方法:

由于你的正则表达式中的catastrophic backtracking,它变慢了:

您可以使用此正则表达式修复灾难性回溯:

^(?P<parts>(?:[\w-]+/)*[\w-]+)/$

根据上面的链接:

The solution to avoid catastrophic backtracking is simple. When nesting repetition operators, make absolutely sure that there is only one way to match the same match.

标签:python,regex,regex-greedy
来源: https://codeday.me/bug/20190623/1269663.html