简体   繁体   English

使用Ruby使用Regex验证字符串

[英]Validate a string with Regex using Ruby

I have to validate a range of strings: 00001 up to 01200 我必须验证字符串范围:00001到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 第一位数字为零第二位数字必须为0或1第三位数字必须为0,1或2最后两个数字可以为任何数字

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? 使用Range#include的非正则表达式解决方案 :

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

Non-regex solution using Range#cover? 使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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