Help with regex in a line of text in C #

im trying to check a line of text that should be in the following format,

The number "1", followed by a semicolon, followed by only 1 to three numbers - it will look something like this.

1: 1 (correct)
1:34 (layout)
1: 847 (correct)
1: 2322 (incorrect)

There can be no letters or anything else but numbers.

Does anyone know how I can do this with REGEX? and in c #

+4
source share
1 answer

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" .

+7
source

All Articles