The following template will do this for you:
^1:\d{1,3}$
Code example:
string pattern = @"^1:\d{1,3}$"; Console.WriteLine(Regex.IsMatch("1:1", pattern)); // true Console.WriteLine(Regex.IsMatch("1:34", pattern)); // true Console.WriteLine(Regex.IsMatch("1:847", pattern)); // true Console.WriteLine(Regex.IsMatch("1:2322", pattern)); // false
For easier access, you should probably put the check in a separate method:
private static bool IsValid(string input) { return Regex.IsMatch(input, @"^1:\d{1,3}$", RegexOptions.Compiled); }
Template Explanation:
^ - the start of the string 1 - the number '1' : - a colon \d - any decimal digit {1,3} - at least one, not more than three times $ - the end of the string
The ^ and $ characters make the pattern match the complete string, instead of finding valid strings embedded in a large string. Without them, the template will also correspond to strings like "1:2322" and "the scale is 1:234, which is unusual" .
source share