首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >验证Ruby中的用户日期输入

验证Ruby中的用户日期输入
EN

Stack Overflow用户
提问于 2018-01-19 03:58:17
回答 1查看 169关注 0票数 2

我正在尝试在我的ruby脚本中验证正确的日期输入。

当我运行脚本时,它只要求输入日期两次,无论它是否正确。

有没有人能告诉我哪里出错了?

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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/是真的。

您的输入也不会被捕获,因此无法与正则表达式进行比较。

代码语言:javascript
复制
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喜欢两个空格)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48329360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档