9

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.

3
  • What have you tried? Best to read some documentation or google before asking your question. Commented Jul 27, 2013 at 15:35
  • 2
    What do you want '1,22' to be interpreted ? Commented Jul 27, 2013 at 15:40
  • Whatever you wrote as code is not valid. Is it an array of strings? Commented Jul 27, 2013 at 15:41

6 Answers 6

15
a.map {|i| i.gsub(/[^\d,\.]/, '')}
# => ["1.22", "1,22", "1.22", "1,22", "1.22"] 
Sign up to request clarification or add additional context in comments.

Comments

12

Try this:

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

3 Comments

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.)
@InspectorElement Add \r and \n to the list of characters, then they won't be removed.
Thank you, it worked for me. Just one thing if you want to exclude comma then simply use gsub(/[^0-9.]/, "")
2

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]

Comments

0

you can replace all white space, all '$' by ''

1 Comment

How would you do that in ruby?
0

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"]

Comments

-1
str = "a1234c324ee4r"    
str.delete("^0-9")

It deletes all the characters from string and return all the integers

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.