Is there another way to write the following?
string input;
var match = Regex.Match(input, @"Type1");
if (!match.Success)
{
match = Regex.Match(input, @"Type2");
}
if (!match.Success)
{
match = Regex.Match(input, @"Type3");
}
Basically, I want to run my string thru a gammut of expressions and see which one sticks.
var patterns = new[] { "Type1", "Type2", "Type3" };
Match match;
foreach (string pattern in patterns)
{
match = Regex.Match(input, pattern);
if (match.Success)
break;
}
or
var patterns = new[] { "Type1", "Type2", "Type3" };
var match = patterns
.Select(p => Regex.Match(input, p))
.FirstOrDefault(m => m.Success);
// In your original example, match will be the last match if all are
// unsuccessful. I expect this is an accident, but if you want this
// behavior, you can do this instead:
var match = patterns
.Select(p => Regex.Match(input, p))
.FirstOrDefault(m => m.Success)
?? Regex.Match(input, patterns[patterns.Length - 1]);
Because LINQ to Objects uses deferred execution, Regex.Match
will only be called until a match is found, so you don't have to worry about this approach being too eager.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With