c# - 正则表达式速度改进 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(/*....*/)
{
/*...*/
}
解决方案
无需先做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
.
推荐阅读
- android - Firestore 地理查询
- python - 从类中的模块导入函数找不到自我
- python - Seaborn 图调整“plotting_context”对于图例标记大小没有按预期工作
- postgresql - 在 Microsoft Server 2016 上使用 Docker 设置 Apache Airflow
- javascript - javascript handleClick-function 语法错误?for循环
- python - 在配对图中,如何不显示置信区间而是显示网格线?
- node-red - 值超出界限节点红色读数浮动
- c++ - 如何使用 cmake 包含 .so 库
- asp.net-core - 使用 Mailkit 的 asp.net 核心 mvc 应用程序中选定下拉值的 NULLReferenceException
- oracle - Oracle join 返回太多行