views:

163

answers:

1

Hi, im trying to validate a string of text that must be in the following format,

The number "1" followed by a semicolon followed by between 1 and three numbers only - it would look something like this.

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

There can be no letters or anything else except numbers.

Does anyone know how i can make this with REGEX? and in C#

+4  A: 

The following pattern would do that for you:

^1:\d{1,3}$

Sample code:

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 more convenient access you should probably put the validation into a separate method:

private static bool IsValid(string input)
{
    return Regex.IsMatch(input, @"^1:\d{1,3}$", RegexOptions.Compiled);
}

Explanation of the pattern:

^     - 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 makes the pattern match the full string, instead of finding valid strings embedded in a larger string. Without them the pattern would also match strings like "1:2322" and "the scale is 1:234, which is unusual".

Fredrik Mörk