简体   繁体   English

为什么/^(.+)+Q$/.test("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)需要这么长时间?

[英]Why does /^(.+)+Q$/.test(“XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX”) take so long?

When I run 我跑的时候

/^(.+)+Q$/.test("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")

in Chrome or IE, it takes ~10 seconds to complete. 在Chrome或IE中,完成需要大约10秒钟。 (Firefox is able to evaluate it almost instantly.) (Firefox几乎可以立即对其进行评估。)

Why does it take so long? 为什么需要这么长时间? (And why/how is Firefox able to do it so quickly?) (为什么Firefox如何能够如此快速地完成它?)

(Of course, I'd never run this particular regex, but I'm hitting a similar issue with the URL regex at http://daringfireball.net/2010/07/improved_regex_for_matching_urls and it seems to boil down to this, ie there are certain URLs which will cause the browser to lock up) (当然,我从来没有运行过这个特殊的正则表达式,但是我在http://daringfireball.net/2010/07/improved_regex_for_matching_urls上遇到了与URL正则表达式类似的问题,它似乎归结为这个,即那里是某些会导致浏览器锁定的URL

For example: 例如:

var re = /\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i;
re.test("http://google.com/?q=(AAAAAAAAAAAAAAAAAAAAAAAAAAAAA")

As indicated by thg435, it sounds like catastrophic back-tracking. 如thg435所示,这听起来像是灾难性的回溯。 There's an excellent article on this, Regular Expression Matching Can Be Simple And Fast . 有一篇很好的文章, 正则表达式匹配可以简单快速

It describes an efficient approach known as Thompson NFA. 它描述了一种称为Thompson NFA的有效方法。 As noted, though, this does not support all features of modern regexes. 但是,如上所述,这并不支持现代正则表达式的所有功能。 For instance, it can't do backreferences. 例如,它无法进行反向引用。 However, as suggested in the article: 但是,正如文章中所建议的那样:

"Even so, it would be reasonable to use Thompson's NFA simulation for most regular expressions, and only bring out backtracking when it is needed. A particularly clever implementation could combine the two, resorting to backtracking only to accommodate the backreferences." “即便如此,对于大多数正则表达式使用Thompson的NFA模拟是合理的,并且只在需要时才进行回溯。一个特别聪明的实现可以将两者结合起来,仅仅为了适应反向引用而进行回溯。”

I suspect Firefox may be doing this. 我怀疑Firefox可能会这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM