如何使用Ruby检查字符串中是否至少包含一个数字?

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

http://public.kvalley.com/regex/regex.asp - Catharsis
5个回答

40

您可以使用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

13

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

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

3
如果忽略正则表达式编译的开销(如果测试在大循环中进行或要检查的字符串非常长,这是公平的),那么你提供的解决方案可能不够高效。对于一个特殊情况,你的解决方案必须遍历整个字符串,而正确的正则表达式只需要找到一个数字就可以停止。 - Bryan Oakley
2
虽然这个可能不是最高效的,但它非常易读,对于某些情况可能更好。 - Erica Tripp

5
if /\d/.match( theStringImChecking ) then
   #yep, there's a number in the string
end

4
!s[/\d/].nil?

可以作为独立函数使用 -
def has_digits?(s)
  return !s[/\d/].nil?
end

或者...将其添加到String类中使其更加方便 -
class String
  def has_digits?
    return !self[/\d/].nil?
  end
end

3
与其使用类似“s =~ /\d/”这样的表达式,我更倾向于使用更短的 s[/\d/],它在未命中时返回 nil(在条件测试中为 false)或命中的索引(在条件测试中为 true)。如果您需要实际值,请使用 s[/(\d)/, 1]。
这两种方法应该是相同的,主要取决于程序员个人选择。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接