如何使用 Ruby 检查字符串中是否至少包含一个数字? [英] How do I check if a string has at least one number in it using Ruby?

查看:30
本文介绍了如何使用 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

这篇关于如何使用 Ruby 检查字符串中是否至少包含一个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆