问题
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