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));
}
}