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]
Share:
11,442

Related videos on Youtube

user1859243
Author by

user1859243

Updated on July 04, 2022

Comments

  • user1859243
    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
      bsd over 10 years
      What do you want '1,22' to be interpreted ?
  • likeitlikeit
    likeitlikeit over 10 years
    How would you do that in ruby?
  • Olivia Steger
    Olivia Steger about 7 years
    This 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
    ProgramFOX about 7 years
    @InspectorElement Add \r and \n to the list of characters, then they won't be removed.
  • Touseef Murtaza
    Touseef Murtaza over 4 years
    Thank you, it worked for me. Just one thing if you want to exclude comma then simply use gsub(/[^0-9.]/, "")

Related