【问题标题】:Regex to parse Email - high CPU load [duplicate]正则表达式解析电子邮件 - 高 CPU 负载 [重复]
【发布时间】:2012-09-30 16:14:48
【问题描述】:

可能重复:
c# regex email validation

我目前正在使用以下正则表达式和代码从 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. 如果字符串是使用正则表达式的电子邮件,则不要匹配,请使用库(例如,使用正则表达式的复杂性参见ex-parrot.com/pdw/Mail-RFC822-Address.html
  • 我只能想到一个从任意 HTML 文档中提取电子邮件地址的原因,而且我当然不会支持。
  • 请阅读:regular-expressions.info/catastrophic.html。这就是您的正则表达式速度慢且 CPU 负载高的原因。
  • @Elvin:阅读全文 ;-)
  • @CodeCaster:这与正则表达式引擎中几乎普遍存在的灾难性回溯问题相同。但是 .NET 有一个 JavaScript 没有的解决方案(甚至在我对 JavaScript 问题的回答中也有概述)。

标签: c# regex


【解决方案1】:

为了详细说明@Joey 的建议,我建议逐行检查您的输入,删除任何不包含@ 的行,并将您的正则表达式应用于包含的行。这应该会大大减少负载。

private List<Match> find_emails_matches()
{
    List<Match> result = new List<Match>();

    using (FileStream stream = new FileStream(@"C:\tmp\test.txt", FileMode.Open, FileAccess.Read))
    {
        using(StreamReader reader = new StreamReader(stream))
        {
            string pattern = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            Regex regex = new Regex(pattern, RegexOptions.None | RegexOptions.Compiled);

            string line;
            while((line = reader.ReadLine()) != null)
            {
                if (line.Contains('@'))
                {
                    MatchCollection matches = regex.Matches(line); // Here is where it takes time                            
                    foreach(Match m in matches) result.Add(m);
                }
            }
        }
    }

    return result;
}

【讨论】:

  • 效果很好!!非常感谢
  • 我的回答不用细说;对于特定情况,这是错误的。我来自验证角度,而不是提取。
  • 真正聪明的解决方案!
猜你喜欢
  • 1970-01-01
  • 2010-11-03
  • 2010-11-18
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
  • 2014-12-09
相关资源
最近更新 更多