首页 > 解决方案 > 为什么这个正则表达式会挂起浏览器?

问题描述

我正在尝试调试一个挂起 Chrome 和 Firefox(虽然不是 Safari)的奇怪问题。

我把它归结为这段代码(它来自第 3 方,但我的代码正在与之交互):

var str = 'pymxPYMxau-trade-in-calculator-1xPYMxheightxPYMx950'; // String is coming from a dynamic object, but this is the value that gets passed to the pattern matching

var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
        '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
        '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
        '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
        '(\\#[-a-z\\d_]*)?$','i'); // fragment locator

pattern.test(str); // This line hangs the browser

注意:尝试此代码需要您自担风险,它会挂起 Chrome!

这里发生了什么?

标签: javascriptregexperformance

解决方案


推荐阅读