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

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

问题描述:

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

I need to check to see if a string contains at least one number in it using Ruby (and I assume some sort of regex?).

我该怎么做?

您可以将 String 类的 =~ 方法与正则表达式 /\d/一起使用 作为参数.

You can use the String class's =~ method with the regex /\d/ as the argument.

这是一个例子:

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