[英]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 .
我需要删除除digits
和,
和 之外的所有字符.
. . So I need to get a value that always can be parsed as Float.所以我需要得到一个总是可以解析为 Float 的值。
a.map {|i| i.gsub(/[^\d,\.]/, '')}
# => ["1.22", "1,22", "1.22", "1,22", "1.22"]
Try this:试试这个:
yourStr.gsub(/[^0-9,.]/, "")
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
),这应该将您的值转换为浮点数:
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]
you can replace all white space, all '$'
by ''
你可以用''替换所有空格,所有'$'
''
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"]
str = "a1234c324ee4r"
str.delete("^0-9")
It deletes all the characters from string and return all the integers它从字符串中删除所有字符并返回所有整数
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 .
我需要删除除digits
和,
和 之外的每个字符.
. . So I need to get a value that always can be parsed as Float.所以我需要得到一个总是可以解析为 Float 的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.