Grouch
Grouch

Reputation: 101

RegEx to match 2-digit number in certain range

I need to create a RegEx to verify the string input to a text box is exactly 2 digits long and is within the range 01-25 or 99.

I am new to creating my own RegEx and came up with:

[01-25,99]{2}

This verifies the number is 2 digits long, but it finds many matches outside of the indicated range.

Upvotes: 2

Views: 4544

Answers (5)

repzero
repzero

Reputation: 8412

Also like this [0][1-9]|[1][0-9]|[2][0-5]|[99]

Upvotes: 0

Bohemian
Bohemian

Reputation: 424983

Character classes can contain character ranges, not value ranges.

Try this alternation:

0[1-9]|1\d|2[0-5]|99

If you want to limit the entire input to be such, wrap in ^ and $:

^0[1-9]|1\d|2[0-5]|99$

Upvotes: 4

R Nar
R Nar

Reputation: 5515

the way that regex works is as individual numbers, not as a range like you would assume. This means that your pattern :

[01-25,99]

would actually match anything that has a 0,1-2,5, a comma, or a 9 (saying it twice doesn't make a difference), and putting `{2} means that you are matching any string that has both of these in a row.

since it was answered while I was typing this, look at the pattern sln posted for one that should work.

Upvotes: 1

MrJomp
MrJomp

Reputation: 135

Maybe something as dumb as (0[1-9]|1[0-9]|2[0-5]|99)

Upvotes: 1

user557597
user557597

Reputation:

This should work:

 # ^(?:0[1-9]|1\d|2[0-5]|99)$

 ^ 
 (?:
      0 [1-9] 
   |  1 \d 
   |  2 [0-5] 
   |  99
 )
 $

Upvotes: 2

Related Questions