我需要检查一个字符串中是否至少包含一个数字,使用Ruby(我假设要使用某种正则表达式?)。我该怎么做?
您可以使用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
或者,不使用正则表达式的方式:
def has_digits?(str)
str.count("0-9") > 0
end
if /\d/.match( theStringImChecking ) then
#yep, there's a number in the string
end
!s[/\d/].nil?
def has_digits?(s)
return !s[/\d/].nil?
end
class String
def has_digits?
return !self[/\d/].nil?
end
end