Reputation: 315
Please, help me with a regexp for the next 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 remove every character except digits
and ,
and .
. So I need to get a value that always can be parsed as Float.
Upvotes: 9
Views: 12935
Reputation: 19
str = "a1234c324ee4r"
str.delete("^0-9")
It deletes all the characters from string and return all the integers
Upvotes: -1
Reputation: 13574
To extract the 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 like 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]
Upvotes: 2
Reputation: 118261
Another one:
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"]
Upvotes: 0
Reputation: 29124
a.map {|i| i.gsub(/[^\d,\.]/, '')}
# => ["1.22", "1,22", "1.22", "1,22", "1.22"]
Upvotes: 14