在简化示例中,有两个正则表达式,一个区分大小写,另一个不区分大小写。想法是有效地创建一个IEnumerable集合(请参见下面的“组合”),将结果组合起来。
string test = "abcABC";
string regex = "(?<grpa>a)|(?<grpb>b)|(?<grpc>c)]";
Regex regNoCase = new Regex(regex, RegexOptions.IgnoreCase);
Regex regCase = new Regex(regex);
MatchCollection matchNoCase = regNoCase.Matches(test);
MatchCollection matchCase = regCase.Matches(test);
// Combine matchNoCase and matchCase into an IEnumerable
IEnumerable<Match> combined = null;
foreach (Match match in combined)
{
// Use the Index and (successful) Groups properties
//of the match in another operation
}
实际上,MatchCollections可能包含数千个结果,并使用长动态创建的正则表达式频繁运行,因此我想避免将结果复制到数组等。我仍然在学习LINQ,并且对如何将这些结合在一起,或者将对已经很缓慢的过程造成性能影响。
这里有三个步骤:
MatchCollection
转换为IEnumerable<Match>
Match.Success
属性是否为真过滤代码:
IEnumerable<Match> combined = matchNoCase.OfType<Match>().Concat(matchCase.OfType<Match>()).Where(m => m.Success);
这样做会创建一个新的枚举器,该枚举器仅在获取下一个结果时才执行每个步骤,因此最终只对每个集合进行一次枚举,总计。例如,Concat()将仅在第一个用尽后开始执行第二个枚举。
标记为正确的答案会创建一个IEnumerable,每个匹配项都有两个。正确的组合方式如下:
var combined = matches.Where(e=>e.Success).Select(e=>e.Value);