Make two different regular expressions. The first will match your longer option, and if that doesn't work, the second will match your shorter option.
string input = "hello world"; string patternFull = "hello world"; Regex regexFull = new Regex(patternFull, RegexOptions.IgnoreCase); var matches = regexFull.Matches(input); if (matches.Count == 0) { string patternShort = "hello"; Regex regexShort = new Regex(patternShort, RegexOptions.IgnoreCase); matches = regexShort.Matches(input); }
In the end, matches will be printed “full” or “short”, but first “full” will be checked and there will be a short circuit if it is true.
You can wrap logic in a function if you plan to name it many times. This is what I came up with (but there are many other ways to do this).
public bool HasRegexMatchInOrder(string input, params string[] patterns) { foreach (var pattern in patterns) { Regex regex = new Regex(pattern, RegexOptions.IgnoreCase); if (regex.IsMatch(input)) { return true; } } return false; } string input = "hello world"; bool hasAMatch = HasRegexMatchInOrder(input, "hello world", "hello", ...);
source share