How to remove all characters from string except numbers, "," and "." using Ruby?
11,442
Solution 1
a.map {|i| i.gsub(/[^\d,\.]/, '')}
# => ["1.22", "1,22", "1.22", "1,22", "1.22"]
Solution 2
Try this:
yourStr.gsub(/[^0-9,.]/, "")
Solution 3
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]
Related videos on Youtube
Author by
user1859243
Updated on July 04, 2022Comments
-
user1859243 almost 2 years
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.-
bsd over 10 yearsWhat do you want '1,22' to be interpreted ?
-
-
likeitlikeit over 10 yearsHow would you do that in ruby?
-
Olivia Steger about 7 yearsThis was so helpful! Is there any way to keep line breaks in the code? (I'm trying to make a program to clean up a CSV file.)
-
ProgramFOX about 7 years@InspectorElement Add
\r
and\n
to the list of characters, then they won't be removed. -
Touseef Murtaza over 4 yearsThank you, it worked for me. Just one thing if you want to exclude comma then simply use gsub(/[^0-9.]/, "")