c# - How can I find the first regex that matches my input in a list of regexes? -
c# - How can I find the first regex that matches my input in a list of regexes? -
is there way write 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, want run string thru gammut of expressions , see 1 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 original example, match lastly match if // unsuccessful. expect accident, if want // behavior, can instead: var match = patterns .select(p => regex.match(input, p)) .firstordefault(m => m.success) ?? regex.match(input, patterns[patterns.length - 1]);
because linq objects uses deferred execution, regex.match
called until match found, don't have worry approach beingness eager.
c# regex
Comments
Post a Comment