更快地替换正则表达式

Svi*_*ack 6 c# regex performance

我在课堂上有大约100个Regex电话,每个电话都覆盖了文本协议中不同类型的数据,但我有很多文件并且基于分析regex占用了我的代码的88%.

很多这类代码:

{
  Match m_said = Regex.Match(line, @"(.*) said,", RegexOptions.IgnoreCase);
  if (m_said.Success)
  {
    string playername = ma.Groups[1].Value;
    // some action
    return true;
  }
}

{
  Match ma = Regex.Match(line, @"(.*) is connected", RegexOptions.IgnoreCase);
  if (ma.Success)
  {
    string playername = ma.Groups[1].Value;
    // some action
    return true;
  }
}
{
  Match ma = Regex.Match(line, @"(.*): brings in for (.*)", RegexOptions.IgnoreCase);
  if (ma.Success)
  {
    string playername = ma.Groups[1].Value;
    long amount = Detect_Value(ma.Groups[2].Value, line);
    // some action
    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法替换Regex其他一些更快的解决方案?

Sek*_*eki 8

对于在循环中测试的正则表达式,通常在循环之外将它们预编译并在循环内部进行测试通常会更快.

您需要先使用各自的模式声明不同的正则表达式,然后仅Match()在第二步中调用文本进行测试.