我目前使用下面的正則表達式和代碼解析從HTML文檔的電子郵件地址
string pattern = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
Regex regex = new Regex(
pattern,
RegexOptions.None | RegexOptions.Compiled);
MatchCollection matches = regex.Matches(input); // Here is where it takes time
MessageBox.Show(matches.Count.ToString());
foreach (Match match in matches)
{
...
}
例如:
嘗試解析http://www.amelia.se/Pages/Amelia-search-result-page/?q=
在RegexHero上它崩潰了。
有什麼辦法來優化這個嗎?
1.不要使用正則表達式解析HTML,請使用正確的解析器。 2.如果字符串是使用正則表達式的電子郵件,請使用庫(例如使用正則表達式的複雜性,請參見http://www.ex-parrot.com/pdw/Mail-RFC822 -Address.html) – Anders
我只能想到從任意HTML文檔中提取電子郵件地址的原因,這是我當然不會支持的。 – Philipp
請閱讀:http://www.regular-expressions.info/catastrophic.html。這就是你的正則表達式很慢並且CPU負載很高的原因。 –