Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the first regex that matches my input in a list of regexes?

Tags:

c#

regex

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.

like image 427
Rod Avatar asked Jan 13 '12 21:01

Rod


1 Answers

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.

like image 157
Matthew Avatar answered Sep 24 '22 18:09

Matthew