Yes, I would write this in such a way as to avoid repeating the regular expression:
match = Regex.Match(input, @"Type1|Type2|Type3");
if (match.Success)
{
foreach (Capture capture in match.Captures)
{
switch (capture.Value)
{
case "Type1":
break;
case "Type2":
break;
case "Type3":
break;
}
}
}
Alternatively, if you have an arbitrary list of templates that you want to check:
match = Regex.Match(input, string.Join("|", patterns));
if (match.Success)
{
return match.Captures[0].Value;
return match.Captures.OfType<Capture>().Select(capture => capture.Value);
}
, . , , .
- "Pattern" , , :
EDIT: ,
int i = 0;
var mapOfGroupNameToPattern = patterns.ToDictionary(pattern => "Pattern" + (i++));
match = Regex.Match(input, string.Join("|", mapOfGroupNameToPattern.Select(x => "(?<" + x.Key + ">" + x.Value + ")")));
if (match.Success)
{
foreach (var pattern in mapOfGroupNameToPattern)
{
if (match.Groups[pattern.Key].Captures.Count > 0)
{
return pattern.Value;
}
}
}