Check if string contains only positive numbers in Ruby

I am really new to ruby and want to know if it is 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 
+7
string ruby
source share
5 answers

Of course, Regexp is good for this:

 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 method is not valid for your case, because it will return a number if the string is even with letters:

 string = "123abcd" string.to_i # 123 
+5
source share

All other answers so far using regular expressions are ineffective.

 "123abcd" !~ /\D/ # => false "153" !~ /\D/ # => true 
+19
source share
 if '123'.match(/^\d+$/) # code end 
+4
source share

I am using Regexp#=== as shown below:

 str = "123abcd" /^\d+$/ === str # => false # because string not only contains digits str = "153" /^\d+$/ === str # => true # because string only contains digits 

update (considering @sawa comment1 and comment2 )

 str = "123abcd" /\D/ === str # => true # because string contains non-digit str = "153" /\D/ === str # => false # because string doesn't contain any non-digit 
+2
source share

I initially answered this when "only positive numbers" were a requirement, but I see that it was changed to "only positive numbers" (the original wording), which is partially due to the above example (which excludes the interpretation of "12abc34" => true , "12abc-34" => false and does not imply an interpretation of "1.5abc" => true ), I mean "one positive integer". My assumption is more precisely determined by my answer:

 str =~ /^0*[1-9]\d*$/ 

This question raises another: "How many rubists can dance pins on their heads?" Maybe it's just news day. Thanks to @sawa and @Mark for their comments.

0
source share

All Articles