Check if a string contains only comma-separated floats in Ruby

How to check if a string contains only floats, separated by commas without a space. Something like below:

str = "0.0687987167581341,0.120311605902415,89.8399554017928,198.151088713489"  #true
str = "0.068798716758f1341,0.120311605902415, 89.8399554017928,198.151088713489" #False because of "f" in the first value.
str = "0.0687987167581341 0.120311605902415" # False because of no space and comma.

Basically, how can I check if a line is in the form below:

str = "<value>,<value>,<value>" # where value may only contains, integers, floats.
0
source share
3 answers

If the following match is fulfilled, then this means that it strdoes not satisfy the condition.

str =~ /[^\d.,]/

So, accepting the negation:

re = /[^\d.,]/
"0.0687987167581341,0.120311605902415,89.8399554017928,198.151088713489" !~ re
# => true
"0.068798716758f1341,0.120311605902415, 89.8399554017928,198.151088713489" !~ re
# => false
"0.0687987167581341 0.120311605902415" !~ re
# => false
+1
source

How about this regex:

str.split(',').all? {|val| val =~ /\A-?\d+(\.\d+)?\Z/}
+2
source

: , , , , , , . , , -2.1 , -3 . float, , , , .

@Linuxios, . , :

str = "0.0687987167581341,0.120311605902415,89.8399554017928,198.151088713489"

str.split(',').all? { |s| s.to_f.to_s == s.strip }
  #=>true

, , :

str.split(',').all? {|s| s.to_f.to_s == 
  s.match(/^\s*(-)?\s*?0*?(0.\d+?|[1-9]\d*\.\d+?)0*\s*$/)[1..-1].join
+1

All Articles