简体   繁体   English

如何从字符串中删除除数字、“,”和“.”之外的所有字符使用红宝石?

[英]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.

相关问题 删除Ruby字符串中除字母和数字之外的所有字符 - Remove all characters except alphabets and numbers from a Ruby string 如何从Ruby中的字符串中删除所有非ASCII字符 - How to remove all non - ASCII characters from a string in Ruby Ruby-从字符串中删除所有其他字符 - Ruby - Remove all other characters from a String 除了ruby中的特殊字符外,如何匹配所有语言的字符 - How to match characters from all languages, except the special characters in ruby 如何替换字符串中除某些字符以外的所有字符(在Ruby中) - How to substitute all characters in a string except for some (in Ruby) 正则表达式(ruby)删除字符集的所有实例(当它们位于字符串开头时) - Regex (ruby) to remove all instances of a set of characters EXCEPT when they are at the start of a string 如何使用 RegExp 从文本中删除除 ä、ö 和 ü 之外的所有非单词字符 - How to remove all non word characters except ä,ö and ü from a text using RegExp 如何使用Ruby从字符串中删除括号内的所有符号? - How to remove all symbols inside brackets from string using Ruby? 使用正则表达式从除撇号之外的字符串中去除所有字符和标点符号 - Using regex to strip all characters and punctuation from a string except apostrophe 如何在Ruby中的特定索引处从String中删除字符 - How to remove characters from String at specific index in Ruby
相关标签
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM