加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 更快地替换正则表达式

发布时间:2020-12-15 18:30:13 所属栏目:百科 来源:网络整理
导读:我在课堂上有大约100个 Regex调用,每个调用覆盖文本协议中的不同类型的数据,但我有很多文件,并且基于分析正则表达式占用了我的代码的88%. 很多这类代码: { Match m_said = Regex.Match(line,@"(.*) said,",RegexOptions.IgnoreCase); if (m_said.Success)
我在课堂上有大约100个 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;
  }
}

有没有办法用其他更快的解决方案取代Regex?

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读