c# - 提高正则表达式效率

标签 c# regex

我有大约 10 万封 Outlook 邮件项目,每个正文大约有 500-600 个字符。我有一个包含 580 个关键字的列表,必须搜索每个正文,然后将这些词附加在底部。

我相信我已经提高了大部分功能的效率,但仍然需要很多时间。即使是 100 封电子邮件,也需要大约 4 秒。

我为每个关键字列表运行两个函数(每个列表 290 个关键字)。

       public List<string> Keyword_Search(HtmlNode nSearch)
    {
        var wordFound = new List<string>();
        foreach (string currWord in _keywordList)
        {
            bool isMatch = Regex.IsMatch(nSearch.InnerHtml, "\\b" + @currWord + "\\b",
                                                  RegexOptions.IgnoreCase);
            if (isMatch)
            {
                wordFound.Add(currWord);
            }
        }
        return wordFound;
    }

有什么方法可以提高这个函数的效率吗?

另一件可能会减慢速度的事情是我使用 HTML Agility Pack 在一些节点中导航并拉出正文 (nSearch.InnerHtml)。 _keywordList 是列表项,而不是数组。

最佳答案

我假设 COM 调用 nSearch.InnerHtml 非常慢,并且您对要检查的每个单词都重复调用。您可以简单地缓存调用的结果:

public List<string> Keyword_Search(HtmlNode nSearch)
{
    var wordFound = new List<string>();

    // cache inner HTML
    string innerHtml = nSearch.InnerHtml;

    foreach (string currWord in _keywordList)
    {
        bool isMatch = Regex.IsMatch(innerHtml, "\\b" + @currWord + "\\b",
                                              RegexOptions.IgnoreCase);
        if (isMatch)
        {
            wordFound.Add(currWord);
        }
    }
    return wordFound;
}

Jeff Yates 建议的另一种优化。例如。通过使用单一模式:

string pattern = @"(\b(?:" + string.Join("|", _keywordList) + @")\b)";

关于c# - 提高正则表达式效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2545482/

相关文章:

java - 正则表达式导致模式语法异常

regex - 如何使用sed用逗号替换空格?

regex - 用于分隔多个可选匹配项的 Postgres 正则表达式

c# - 在同一 Razor 页面上处理多个表单

c# - WCF - 从接口(interface)契约重新生成客户端代码

c# - 无法使用 MemoryStream 合并 2 个 PDF

c# - *.csproj 中的 usevshostingprocess 是什么?

c# - 将一个对象转换为另一种类型

c# - 将 [A][B] 解析为 A 和 B 的正则表达式

javascript - JavaScript 中的 RegExp,当量词是模式的一部分时