正则表达式C#有2种模式。可以知道哪种模式匹配? [英] Regex C# with 2 patterns. Possible to know which pattern matched?

查看:94
本文介绍了正则表达式C#有2种模式。可以知道哪种模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 Regex regex = new Regex(@"a|b");
Match match = regex.Match(line);
 if (match.Success)
{
}





我想知道该行匹配a或b..因为基于这个结果我想做不同的事情



我尝试过:



我最好的解决办法是拆分正则表达式本身





I want to know if the line matched on "a" or "b" .. because based on that result i want to do different things

What I have tried:

my best solution was to split the regex itself

 if (match1.Success)
{
}
if (match2.Success)
{
}

推荐答案

另一种方法是使用组:正则表达式参考:捕获组和反向引用 [ ^ ]我使用命名组使其更明显:

The other alternative is to use groups: Regular Expression Reference: Capturing Groups and Backreferences[^] I'd use Named groups to make it more obvious:
(?<GroupA>a)|(?<GroupB>b)

这样你可以检查Regex.Groups属性命名并确定匹配的内容。

That way you can inspect the Regex.Groups property by name and determine which matched.


以下是使用GetGroupNames的示例捕获组名的方法。在底部你可以写一个if语句,f matchedGroupName ==abc然后......



reg_multiple C# - rextester [ ^ ]
Here is an example using GetGroupNames method to capture the group name. At the bottom you can write an if statement, f matchedGroupName == "abc" then ...

reg_multiple C# - rextester[^]


这篇关于正则表达式C#有2种模式。可以知道哪种模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆