Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 872
user1859243 Avatar asked Jul 27 '13 15:07

user1859243


People also ask

How do I remove a character from a string in Ruby?

In Ruby, we can permanently delete characters from a string by using the string. delete method. It returns a new string with the specified characters removed.

How do I remove all special characters from a string in Ruby?

Delete - (. Delete is the most familiar Ruby method, and it does exactly what you would think: deletes a sub-string from a string. It will search the whole string and remove all characters that match your substring. The downside of delete is that it can only be used with strings, not RegExs.

What does =~ mean in Ruby?

=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.

How do you get rid of the N at the end of a string in Ruby?

You need to use "\n" not '\n' in your gsub.


1 Answers

a.map {|i| i.gsub(/[^\d,\.]/, '')}
# => ["1.22", "1,22", "1.22", "1,22", "1.22"] 
like image 58
Santhosh Avatar answered Sep 18 '22 23:09

Santhosh