首页 > 解决方案 > 正则表达式速度改进 C#

问题描述

我正在使用正则表达式处理几个文本文件。文本文件中的行可以是几个预选模式中的任何一个(最多 8 个模式)。下面是示例

 static Regex regExCase1= new Regex(@"^\s+Result\s(\S+)\s\S+\,\s(\S+)\s\S\sLocation\sID\s(\S+)",,RegexOptions.IgnorePatternWhitespace);
 static Regex regExCase2= new Regex(@"^\s+Result\s(\S+)\s\S+,\s+\S\sLocation\sAt\s\S(\d)",,RegexOptions.IgnorePatternWhitespace);

正则表达式非常优化。它最初是用 VB.NET 编写的,然后转换为 C#。我相信在检查每个模式两次时会浪费很多时间,一次使用 IsMatch(),另一次使用 Matches()。我正在考虑更新代码以仅考虑模式检查一次,并想知道是否有其他方法可以做到这一点。有人可以建议我是否值得更新代码。由于更改需要更改逻辑,因此反馈将非常有用。

if (regExCase1.IsMatch(TextLine))
{
      matches = regExCase1.Matches(TextLine);
      Param1 = matches[0].Groups[1].Value;
      Param2= matches[0].Groups[2].Value;
      Param3= matches[0].Groups[3].Value;
      statusCase1= true;  //bool
 }
 else if (regExCase2.IsMatch(TextLine))
 {
      matches = regExCase2.Matches(TextLine);
      Param1 = matches[0].Groups[1].Value;
      Param2= matches[0].Groups[2].Value;
      Param3= matches[0].Groups[3].Value;
      statusCase2= true;  //bool
} 
elseif(/*....*/)
{
   /*...*/
}

标签: c#regex

解决方案


无需先做IsMatch,直接使用即可Matches,避免双重处理:

var matches = regExCase1.Matches(TextLine);

if(matches != null && matches.Count > 0)
{
    //Process the results
}
else
{
    matches = regExCase2.Matches(TextLine);
    if(matches != null && matches.Count > 0)
    {
        //Process the results
    }
    else
    {
        //Other cases
    }
}

此外,您的代码仅检查 上的第一个结果MatchCollection,如果每次检查只能有一个结果,则使用Match而不是Matches.


推荐阅读