【问题标题】:Regex to eliminate negative numbers, decimals and alphanumeric data in Ruby正则表达式消除 Ruby 中的负数、小数和字母数字数据
【发布时间】:2013-07-14 11:22:59
【问题描述】:

我正在尝试将正整数分配给项目列表。正整数是用户输入。我正在使用 Ruby 1.9.3-p327

如果用户输入负数(任何

我当前的代码循环内是:-

      input_data = gets.chomp
      while (input_data.to_i <= 0  || input_data.include?(".") || /^[-+]?[0-9]+$/.match(input_data).nil?)
        puts "input_data can't be 0 or a negative integer or in decimal format or alphanumeric. \nPlease input appropriate input_data as a +ve integer "
        input_data = gets.chomp
      end

我相信会有更优化的方法来做到这一点。我猜它可能正在使用组合的正则表达式检查。我是 Ruby 中正则表达式的新手。有什么建议吗?

谢谢

【问题讨论】:

    标签: regex optimization ruby-1.9.3


    【解决方案1】:

    使用正则表达式:

    input_data = gets.chomp
    while input_data !~ /^[1-9]\d*$/
      puts "input_data can't be 0 or a negative integer or in decimal format or alphanumeric. \nPlease input appropriate input_data as a +ve "
      input_data = gets.chomp
    end
    

    【讨论】:

    • 像魅力一样工作。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 2021-03-30
    • 1970-01-01
    • 2014-06-27
    相关资源
    最近更新 更多