我正在尝试在我的ruby脚本中验证正确的日期输入。
当我运行脚本时,它只要求输入日期两次,无论它是否正确。
有没有人能告诉我哪里出错了?
def get_date(prompt="What is the date of the last scan (YYYYMMDD)")
new_regex = /\A[0-9]{4}[0-1][0-9][0-3][0-9]\z/
print prompt
gets.chomp
if prompt != new_regex
puts "Please enter the date in the correct format"
print prompt
gets.chomp
end
end发布于 2018-01-19 04:14:26
实际上,您的代码试图将提示符与正则表达式模式的相似性进行比较。
/\A[0-9]{4}[0-1][0-9][0-3][0-9]\z/ === /\A[0-9]{4}[0-1][0-9][0-3][0-9]\z/是真的。
您的输入也不会被捕获,因此无法与正则表达式进行比较。
def get_date(prompt="What is the date of the last scan")
new_regex = /\A[0-9]{4}[0-1][0-9][0-3][0-9]\z/
print prompt + " (YYYYMMDD)"
input = gets.chomp
unless (input =~ new_regex) == 0
puts "Please enter the date in the correct format"
get_date(prompt)
end
input
end如果没有匹配项,input =~ new_regex将为空(false)。
(ps Rubyists喜欢两个空格)
https://stackoverflow.com/questions/48329360
复制相似问题