Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

javascript - Why does this regex make Chrome hang?

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?!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...