且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-31 23:06:10

您可以将 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