【问题标题】:How do I check if a string has at least one number in it using Ruby?如何使用 Ruby 检查字符串中是否至少包含一个数字?
【发布时间】:2010-02-08 20:52:03
【问题描述】:

我需要使用 Ruby 检查一个字符串中是否至少包含一个数字(我假设是某种正则表达式?)。

我该怎么做?

【问题讨论】:

标签: ruby regex string numbers


【解决方案1】:

您可以使用String 类的=~ 方法和正则表达式/\d/ 作为参数。

这是一个例子:

s = 'abc123'

if s =~ /\d/         # Calling String's =~ method.
  puts "The String #{s} has a number in it."
else
  puts "The String #{s} does not have a number in it."
end

【讨论】:

    【解决方案2】:

    或者,不使用正则表达式:

    def has_digits?(str)
      str.count("0-9") > 0
    end
    

    【讨论】:

    • 如果您忽略编译正则表达式的开销(如果测试是在一个大循环中完成或要检查的字符串很长,这是公平的),那可能效率较低。对于退化的情况,您的解决方案必须遍历整个字符串,而正确的正则表达式将在找到数字后立即停止。
    • 虽然这可能不是最有效的,但它的可读性非常好,在某些情况下可能会更好。
    【解决方案3】:
    if /\d/.match( theStringImChecking ) then
       #yep, there's a number in the string
    end
    

    【讨论】:

      【解决方案4】:

      我没有使用像“s =~ /\d/”这样的东西,而是选择较短的 s[/\d/],它返回 nil 以表示未命中(在条件测试中为假)或命中索引(在条件测试中也为真)。如果您需要实际值,请使用 s[/(\d)/, 1]

      它应该都是一样的,主要是程序员的选择。

      【讨论】:

        【解决方案5】:
        !s[/\d/].nil?
        

        可以是一个独立的功能 -

        def has_digits?(s)
          return !s[/\d/].nil?
        end
        

        或...将其添加到 String 类中会更方便 -

        class String
          def has_digits?
            return !self[/\d/].nil?
          end
        end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-07-20
          • 1970-01-01
          • 1970-01-01
          • 2012-12-26
          • 1970-01-01
          • 2012-03-24
          • 1970-01-01
          相关资源
          最近更新 更多