Vignesh Murugan
Vignesh Murugan

Reputation: 575

How to validate using Regex

My Requirement is that My first two digits in entered number is of the range 00-32.. How can i check this through regex in C#? I could not Figure it out !!`

Upvotes: 0

Views: 102

Answers (5)

Alpay
Alpay

Reputation: 1368

You should divide the region as in:

^[012]\d|3[012]

Upvotes: 1

Jerry
Jerry

Reputation: 4408

if(Regex.IsMatch("123456789","^([0-2][0-9]|3[0-2])"))
    // match

Upvotes: 0

Kami
Kami

Reputation: 19407

Try something like

Regex reg = new Regex(@"^([0-2]?[0-9]|3[0-2])$");
Console.WriteLine(reg.IsMatch("00"));
Console.WriteLine(reg.IsMatch("22"));
Console.WriteLine(reg.IsMatch("33"));
Console.WriteLine(reg.IsMatch("42"));

The [0-2]?[0-9] matches all numbers from zero to 29 and the 3[0-2] matches 30-32.

This will validate number from 0 to 32, and also allows for numbers with leading zero, eg, 08.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Since this is almost certainly a learning exercise, here are some hints:

  • Your rexex will be an "OR" | of two parts, both validating the first two characters
  • The first expression part will match if the first character is a digit is 0..2, and the second character is a digit 0..9
  • The second expression part will match if the first character is digit 3, and the second character is a digit 0..2

To match a range of digits, use [A-B] range, where A is the lower and B is the upper bound for the digits to match (both bounds are inclusive).

Upvotes: 4

James
James

Reputation: 82096

Do you really need a regex?

int val;
if (Int32.TryParse("00ABFSSDF".Substring(0, 2), out val))
{
    if (val >= 0 && val <= 32)
    {
        // valid
    }
}

Upvotes: 4

Related Questions