Reputation: 575
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
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
Reputation: 726479
Since this is almost certainly a learning exercise, here are some hints:
|
of two parts, both validating the first two characters3
, 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
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