Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 提取匹配的组名:更干净的方法吗?_C#_Regex - Fatal编程技术网

C# 提取匹配的组名:更干净的方法吗?

C# 提取匹配的组名:更干净的方法吗?,c#,regex,C#,Regex,假设我有一个模式的形式是“((?foo)|(?bar)|…)”。可能还有更多的条件。如果我想知道我找到了哪个分组(例如,搜索12bar34将返回“sad”),有没有比现在的代码更干净的方法 Regex objRegex = new Regex("((?<happy>foo)|(?<sad>bar))"); Match objMatch = objRegex.Match("12bar34"); for (int i = 0; i < objMatch.

假设我有一个模式的形式是
“((?foo)|(?bar)|…)”
。可能还有更多的条件。如果我想知道我找到了哪个分组(例如,搜索
12bar34
将返回
“sad”
),有没有比现在的代码更干净的方法

Regex objRegex = new Regex("((?<happy>foo)|(?<sad>bar))");
Match objMatch = objRegex.Match("12bar34");        
for (int i = 0; i < objMatch.Groups.Count; ++i)
{
    int tmp;
    if (!String.IsNullOrEmpty(objMatch.Groups[i].Value) &&
        !Int32.TryParse(objRegex.GroupNameFromNumber(i), out tmp))
    {
        //The name of the grouping.
        Trace.WriteLine(objRegex.GroupNameFromNumber(i));
    }
}
Regex objRegex=newregex(((?foo)|(?bar));
Match objMatch=objRegex.Match(“12bar34”);
对于(int i=0;i

请注意,这也将
“0”
视为一个组(整个匹配),所以如果你不想要的话,你可能需要过滤掉它。

成功
是我所缺少的。哈哈,我只是编辑我的答案来摆脱LINQ,我认为它并没有真正的帮助。巧合。干杯。是的,我删除了我的答案,因为你的答案与我的答案非常接近,发布我自己的版本实际上并没有添加任何内容。实际上,我只是跟踪了哪个组号对应哪个名字。在上下文中,这种方法使事情变得更好。
成功
仍然非常重要。我还通过不在0处启动
for
循环来摆脱
tryParse
foreach(string groupName in objRegex.GetGroupNames())
{
   if (objMatch.Groups[groupName].Success)
      Trace.WriteLine(groupName);
}