How to remove all characters from a string except digits, "," and ".". using Ruby?

Please help me with a regex for the following task: I have a "cost" column in some table, but the values ​​there are different:

['1.22','1,22','$1.22','1,22$','$ 1.22'] 

I need to delete every character except digits and , and . . Therefore, I need to get a value that can always be analyzed as a Float.

+6
source share
6 answers
 a.map {|i| i.gsub(/[^\d,\.]/, '')} # => ["1.22", "1,22", "1.22", "1,22", "1.22"] 
+10
source

Try the following:

 yourStr.gsub(/[^0-9,.]/, "") 
+8
source

To extract numbers:

 a = ["1.22", "1,22", "$1.22", "1,22$", "$ 1.22"] a.map {|s| s[/[\d.,]+/] } #=> ["1.22", "1,22", "1.22", "1,22", "1.22"] 

Assuming commas , should be treated as decimal points . (as in '1,22' β†’ 1.22 ), this should convert your values ​​to float:

 a = ["1.22", "1,22", "$1.22", "1,22$", "$ 1.22"] a.map {|s| s[/[\d.,]+/].gsub(',','.').to_f } #=> [1.22, 1.22, 1.22, 1.22, 1.22] 
+1
source

you can replace all spaces, all '$' with ''

0
source

Other:

 a= ['1.22','1,22','$1.22','1,22$','$ 1.22'] a.map{|i| i[/\d+.\d+/]} # => ["1.22", "1,22", "1.22", "1,22", "1.22"] 
0
source

"hello" .tr ('el', 'ip') # => "hippo" try this.

http://www.ruby-doc.org/core-1.9.3/String.html

-3
source

Source: https://habr.com/ru/post/950424/


All Articles