在简化的例子中,有2个正则表达式,一个区分大小写,另一个不是.这个想法将是有效地创建一个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可能包含数千个结果,并可以使用长时间动态创建的REGEXes来运行,所以我想避免将结果复制到数组等.我还在学习LINQ,并且对如何去做模糊将这些或性能与现有的缓慢过程结合起来.@H_502_5@
解决方法
这里有三个步骤:
>将MatchCollection转换为IEnumerable< Match>
连接序列
>根据Match.Success属性是否为true进行过滤@H_502_5@
码:@H_502_5@
IEnumerable<Match> combined = matchNoCase.OfType<Match>().Concat(matchCase.OfType<Match>()).Where(m => m.Success);
这样做会创建一个新的枚举器,它只在执行下一个结果时执行每个步骤,所以最终只能通过每个集合枚举一次.例如,Concat()将在第一次用完后才开始执行第二个枚举器.@H_502_5@