user1859243
user1859243

Reputation: 315

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.

Upvotes: 9

Views: 12935

Answers (6)

S.Shah
S.Shah

Reputation: 19

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

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

Upvotes: -1

tessi
tessi

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

Arup Rakshit
Arup Rakshit

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

Thanh Son Nguyen
Thanh Son Nguyen

Reputation: 184

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

Upvotes: 0

Santhosh
Santhosh

Reputation: 29124

a.map {|i| i.gsub(/[^\d,\.]/, '')}
# => ["1.22", "1,22", "1.22", "1,22", "1.22"] 

Upvotes: 14

ProgramFOX
ProgramFOX

Reputation: 6390

Try this:

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

Upvotes: 12

Related Questions