tags:

views:

27

answers:

1

Suppose I have a pattern in the form of "((?<happy>foo)|(?<sad>bar)|...)" . There could be many more conditions. If I wanted to know which grouping I had found (e.g. searching 12bar34 will return "sad", is there a cleaner way to do it than the code I have now?

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));
    }
}
+2  A: 
foreach(string groupName in objRegex.GetGroupNames())
{
   if (objMatch.Groups[groupName].Success)
      Trace.WriteLine(groupName);
}

Note though that that Regex.GetGroupNamesalso considers "0" to be a group (the entire match), so you may need to filter that out if you don't want it.

Ani
`Success` is what I was missing.
Brian
Haha, I was just editing my answer to get rid of the LINQ, which I thought wasn't really helping. Coincidence. Cheers.
Ani
@Ani: Yeah, I deleted my answer since yours is close enough to my answer that posting my own version doesn't actually add anything. I actually ended up just tracking which group number corresponded to which name. In context, this way of doing it made things better. `Success` was still very relevant, though. I also got rid of the `tryParse` by not starting the `for` loop at 0.
Brian