Regex for a number 1-31 Ruby

感情迁移 提交于 2020-02-23 05:33:13

问题


I am trying to match any number 1-31 (inclusively).

This is the closest I have:

([1-9]|[12]\d|3[01])

But numbers like 324 are accepted.

Any chance there's a regex out there that can capture just 1-31?


回答1:


The following regex satisfies your condition:

^([1-9]|[12][0-9]|3[01])$

Demo here




回答2:


Use a Numeric Comparison Instead

Depending on what you are really trying to do, or to communicate with your code, it may make more sense to simply extract all integers and reject those outside your desired range. For example:

str = '0 1 20 31 324'
str.scan(/\d+/).map(&:to_i).reject { |i| i < 1 or i > 31 }
#=> [1, 20, 31]



回答3:


Try with this one:/^([0-9]|1[0-9]|2[0-9]|3[01])$/

Here an example:

str = STDIN.gets.chomp

if str =~ /^([0-9]|1[0-9]|2[0-9]|3[01])$/
    puts "Match!"
else
    puts "No match!"
end



回答4:


Here's one:

/^(#{(1..31).to_a * '|'})$/
#=> /^(1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)$/


来源:https://stackoverflow.com/questions/26331166/regex-for-a-number-1-31-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!