提高正则表达效率

cam*_*cam 6 c# regex

我有大约100k 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;
    }
Run Code Online (Sandbox Code Playgroud)

反正我有没有提高这个功能的效率?

另一件可能减慢速度的事情是我使用HTML Agility Pack来浏览一些节点并拉出正文(nSearch.InnerHtml)._keywordList是List项,而不是数组.

Dir*_*mar 7

我假设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;
}
Run Code Online (Sandbox Code Playgroud)

另一个优化是Jeff Yates建议的优化.例如,使用单一模式:

string pattern = @"(\b(?:" + string.Join("|", _keywordList) + @")\b)";
Run Code Online (Sandbox Code Playgroud)