检查字符串是否只包含 Ruby 中的正数 [英] Check if string contains only positive numbers in Ruby
本文介绍了检查字符串是否只包含 Ruby 中的正数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对 ruby 真的很陌生,想要知道是否可以使用 regex 来检查字符串是否只包含正数 还是其他功能?
I am really new to ruby and want know if it's possible to check if a string contains only positive numbers using regex or some other function?
str = "123abcd" #return false because it contains alphabets
str = "153" #return true because of all numbers
推荐答案
当然 Regexp
对此有好处:
string = "123abcd"
/^(?<num>\d+)$/ =~ string
num # => nil
string = "123"
/^(?<num>\d+)$/ =~ string
num # => '123' # String
所以如果你需要检查条件:
So if you need to check the condition:
if /^(?<num>\d+)$/ =~ string
num.to_i # => 123
# do something...
end
#to_i
String
的方法对您的情况无效,因为它会返回一个数字,如果字符串与字母是偶数:
#to_i
method of String
isn't valid for your case because it will return a number, if string is even with letters:
string = "123abcd"
string.to_i # 123
这篇关于检查字符串是否只包含 Ruby 中的正数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文