简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM