Why does this regex make Chrome hang?

后端 未结 1 619
名媛妹妹
名媛妹妹 2020-12-20 17:46

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?:\\         


        
1条回答
  •  [愿得一人]
    2020-12-20 17:51

    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?

    0 讨论(0)
提交回复
热议问题