针对Javascript优化Gruber URL正则表达式

时间:2013-07-18 20:26:48

标签: javascript regex performance url gruber

我一直在使用John Gruber的优秀URL正则表达式来匹配非结构化文本消息中的URL。它在大多数时候都非常有效,但我发现了一个根据括号内的内容严重降低性能的情况。

// The URL matching regex.
var urls = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig;

// An example URL that has horrible performance in some modern browsers
var url = "www.linkedin.com/people/~:(id,first-name,last-name,email-address,picture-url,phone-numbers,public-profile-url)";
url.replace(urls, "<a href='$1'>$1</a>");

原始帖子包含正则表达式的多行注释版本,可在此处找到:

http://daringfireball.net/2010/07/improved_regex_for_matching_urls

这是一个JSFiddle,针对这个问题做了一些性能计时:

http://jsfiddle.net/xMePg/4/

及其在Chrome上的输出:

Gruber URL Regex Performance

www.a.com/:(aaaaaaaaaaaaaa)1 MS
www.a.com/:(aaaaaaaaaaaaaaa)0 MS
www.a.com/:(aaaaaaaaaaaaaaaa)0 MS
www.a.com/:(aaaaaaaaaaaaaaaaa)2 MS
www.a.com/:(aaaaaaaaaaaaaaaaaa)3 MS
www.a.com/:(aaaaaaaaaaaaaaaaaaa)5 MS
www.a.com/:(aaaaaaaaaaaaaaaaaaaa)11 MS
www.a.com/:(aaaaaaaaaaaaaaaaaaaaa)22 MS
www.a.com/:(aaaaaaaaaaaaaaaaaaaaaa)44 MS
www.a.com/:(aaaaaaaaaaaaaaaaaaaaaaa)87 MS
www.a.com/:(aaaaaaaaaaaaaaaaaaaaaaaa)174 MS
www.a.com/:(aaaaaaaaaaaaaaaaaaaaaaaaa)348 MS
www.a.com/:(aaaaaaaaaaaaaaaaaaaaaaaaaa)704 MS
www.a.com/:(aaaaaaaaaaaa)(aaaaaaaaaaaaa)0 MS

有人可以确定某些现代浏览器上可能导致匹配时间增加的原因吗?我想要导致匹配失败,或者以某种方式优化正则表达式。

1 个答案:

答案 0 :(得分:1)

删除匹配括号的要求会使其更快。应该适用于绝大多数网址......

m/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)\S+(?:[^\s`!\[\]{};:'".,?«»“”‘’]))/ig;