【发布时间】:2010-02-08 20:52:03
【问题描述】:
我需要使用 Ruby 检查一个字符串中是否至少包含一个数字(我假设是某种正则表达式?)。
我该怎么做?
【问题讨论】:
我需要使用 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/”这样的东西,而是选择较短的 s[/\d/],它返回 nil 以表示未命中(在条件测试中为假)或命中索引(在条件测试中也为真)。如果您需要实际值,请使用 s[/(\d)/, 1]
它应该都是一样的,主要是程序员的选择。
【讨论】:
!s[/\d/].nil?
可以是一个独立的功能 -
def has_digits?(s)
return !s[/\d/].nil?
end
或...将其添加到 String 类中会更方便 -
class String
def has_digits?
return !self[/\d/].nil?
end
end
【讨论】: