0

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 !!`

5 Answers 5

4

Do you really need a regex?

int val;
if (Int32.TryParse("00ABFSSDF".Substring(0, 2), out val))
{
    if (val >= 0 && val <= 32)
    {
        // valid
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

But I should Check they are in the range 00-32 na?How can I do that ?Without Regex if it possible also I am ready to implement that...
@VigneshMurugan yeah I just realised you asked that, thought you were only interested in them being int. I have updated for validation.
4

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

Comments

1

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.

Comments

1

You should divide the region as in:

^[012]\d|3[012]

1 Comment

That's much better :) You do not need to keep the incorrect part of the answer visible - the edit history would keep it for the curious ones, while the rest should see a nice and clean answer.
0
if(Regex.IsMatch("123456789","^([0-2][0-9]|3[0-2])"))
    // match

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.