如何从字符串中删除除数字、“、”和“之外的所有字符。“使用Ruby ?

时间:2022-08-22 12:59:19

Please, help me with a regexp for the next task: I have a 'cost' column in some table, but the values there are different:

请帮助我为下一个任务设置一个regexp:我在某个表中有一个“cost”列,但是其中的值不同:

['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.

我需要删除除数字和…所以我需要得到一个值,这个值总是可以被解析为Float。

6 个解决方案

#1


12  

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

#2


10  

Try this:

试试这个:

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

#3


1  

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:

假设逗号,应该像小数点一样处理。(如在'1,22' -> 1.22),这应将您的值转换为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]

#4


0  

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

你可以替换所有空格,所有的$ by

#5


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

#6


-3  

"hello".tr('el', 'ip') #=> "hippo" try this.

“你好”。tr('el', 'ip') #=> "hippo"试试这个。

http://www.ruby-doc.org/core-1.9.3/String.html

http://www.ruby-doc.org/core-1.9.3/String.html

#1


12  

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

#2


10  

Try this:

试试这个:

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

#3


1  

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:

假设逗号,应该像小数点一样处理。(如在'1,22' -> 1.22),这应将您的值转换为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]

#4


0  

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

你可以替换所有空格,所有的$ by

#5


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

#6


-3  

"hello".tr('el', 'ip') #=> "hippo" try this.

“你好”。tr('el', 'ip') #=> "hippo"试试这个。

http://www.ruby-doc.org/core-1.9.3/String.html

http://www.ruby-doc.org/core-1.9.3/String.html