为什么这个正则表达式会让Chrome挂起? [英] Why does this regex make Chrome hang?

查看:141
本文介绍了为什么这个正则表达式会让Chrome挂起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在Chrome的JS控制台中输入此内容。这是一个正则表达式,我发现要检查是否某个URL是否有效:

 http://www.kvraudio.com/  .match(/ ^(HTTPS:?\ / \ /)([\da-z\ .-] +)\([。az\] {2,6-})([ \ / \w \ .-] *)* \ /?$ /); 

返回匹配,因为它应该是。现在试试这个:

 tp:/www.kvraudio.com/forum/viewtopic.php.match(/ ^( ([\\\\\\\\\\\\\\\\\\\\\\') \\ .-] *)* \ / $ /)?; 

返回空值,因为它不匹配。现在.....试试这个:

 http://www.kvraudio.com/forum/viewtopic.php? p = 5238905\" .match(/ ^(HTTPS:?\ / \ /)([\da-z\ .-] +)\([。az\] {2,6-} )([\ / \w \ .-] *)* \ /?$ /); 

没什么! JS似乎已经死了,或者以某种方式陷入循环。如果我在实际网页中使用上述内容,它将停止响应。甚至不会滚动!任何人对此有任何解释?我做错了什么?!

解决方案

因为你有灾难性的回溯

 ([\ / \\ \\ \\ w \ .-] *)* 

这个表达式应该被修改去除其中一颗星星 ): \\ .-] *)

请注意,灾难性的回溯通常只会在比赛不能成功制作。这就是为什么你给的第一个例子没有任何问题执行。



第二个例子在碰到([...] *)*之前退出) ,所以没有机会让回溯生效。



有关灾难性回溯的更全面解释,请参阅我对此问题的回答:

如何识别邪恶的正则表达式?


Try typing this into Chrome's JS console. It's a regex I found to check if something's a valid URL or not:

"http://www.kvraudio.com/".match(/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/);

A match is returned, as it should be. Now try this:

"tp:/www.kvraudio.com/forum/viewtopic.php".match(/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/);

Null is returned, because it doesn't match. Now..... try this:

"http://www.kvraudio.com/forum/viewtopic.php?p=5238905".match(/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/);

Nothing! JS appears to be dead or stuck in a loop somehow. If I use the above in an actual web page, it stops responding. Won't even scroll! Anyone got any sort of explanation for that then? What have I done wrong?!

解决方案

Because you have catastrophic backtracking:

([\/\w \.-]*)*

This expression should be modified to remove one of the stars (*):

([\/\w \.-]*)

Note that catastrophic backtracking typically only rears its ugly head when a match cannot be made. That's why the first example you gave executes without any issues.

Your second example exits before it hits the ([...]*)*, so there is no opportunity for the backtracking to take effect.

For a more thorough explanation of catastrophic backtracking, see my answer to this question:
How can I recognize an evil regex?

这篇关于为什么这个正则表达式会让Chrome挂起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆