evanx
evanx

Reputation: 1301

Validate a string with Regex using Ruby

I have to validate a range of strings: 00001 up to 01200

I want to make sure:

first digit is zero second digit must be 0 or 1 third digit must be 0,1 or 2 last two numbers can be any digit

so far I have come up with this:

^(0|[0-1][0-2][0-9][0-9])$

but is not working, can you point me on the right direction?

Upvotes: 0

Views: 125

Answers (1)

bjhaid
bjhaid

Reputation: 9752

Non-regex solution using Range#include?:

("00001".."01200").include?("00002")
#=> true

Non-regex solution using Range#cover?:

("00001".."01200").cover?("00002")
#=> true

Regex solution:

/^0([0-1][0-1][0-9]{2}|1200)$/
/^0([0-1][0-1][0-9]{2}|1200)$/ =~ "01200"
=> 0
 /^0([0-1][0-1][0-9]{2}|1200)$/ =~ "00300"
=> nil

Upvotes: 4

Related Questions