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

Shp*_*ord 14 ruby regex string numbers

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

我该怎么办?

Eth*_*han 36

您可以使用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
Run Code Online (Sandbox Code Playgroud)


gle*_*man 8

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

def has_digits?(str)
  str.count("0-9") > 0
end
Run Code Online (Sandbox Code Playgroud)

  • 如果你忽略了编译正则表达式的开销(如果测试是在一个大循环中完成或者要检查的字符串很长),这可能效率较低.对于退化情况,您的解决方案必须遍历整个字符串,而一旦找到数字,正确的正则表达式将立即停止. (3认同)
  • 虽然这可能不是最高效率,但它非常易读,在某些情况下可能会更好。 (2认同)

Jac*_*son 5

if /\d/.match( theStringImChecking ) then
   #yep, there's a number in the string
end
Run Code Online (Sandbox Code Playgroud)