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

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

我该怎么办?

您可以使用String类的=~方法,并使用regex /\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表示未命中(在条件测试中为AKA false)或命中的索引(AKA为true)在条件测试中)。 如果需要实际值,请使用s [/(\ d)/,1]

它应该都是相同的,并且在很大程度上是程序员的选择。

 !s[/\d/].nil? 

可以是一个独立的function –

 def has_digits?(s) return !s[/\d/].nil? end 

或者……将它添加到String类使它更方便 –

 class String def has_digits? return !self[/\d/].nil? end end