简体   繁体   English

如何在ruby中删除所有非数字符号(逗号和破折号除外)

[英]How in ruby delete all non-digits symbols (except commas and dashes)

I meet some hard task for me. 我为我完成了一些艰巨的任务。 I has a string which need to parse into array and some other elements. 我有一个字符串,需要解析为数组和其他一些元素。 I have a troubles with REGEXP so wanna ask help. 我在REGEXP上遇到麻烦,因此想寻求帮助。

I need delete from string all non-digits, except commas (,) and dashes (-) 我需要从字符串中删除所有非数字,但逗号(,)和破折号(-)除外

For example: 例如:

"!1,2e,3,6..-10" => "1,2,3,6-10"
"ffff5-10...." => "5-10"
"1.2,15" => "12,15"

and so. 所以。

[^0-9,-]+

This should do it for you.Replace by empty string .See demo. 这应该为您完成。用empty string替换。请参见演示。

https://regex101.com/r/vV1wW6/44 https://regex101.com/r/vV1wW6/44

We must have at least one non-regex solution: 我们必须至少有一种非正则表达式解决方案:

def keep_some(str, keepers)
  str.delete(str.delete(keepers))
end

keep_some("!1,2e,3,6..-10", "0123456789,-")
  #=> "1,2,3,6-10" 
keep_some("ffff5-10....", "0123456789,-")
  #=> "5-10"
keep_some("1.2,15", "0123456789,-")
  #=> "12,15"
"!1,2e,3,6..-10".gsub(/[^\d,-]+/, '') # => "1,2,3,6-10"

Use String#gsub with a pattern that matches everything except what you want to keep, and replace it with the empty string. String#gsub用于与所有内容(除了要保留的内容)匹配的模式,然后将其替换为空字符串。 In a reguar expression, the negated character class [^whatever] matches everything except the characters in the "whatever", so this works: 在常规表达式中, 否定的字符类 [^whatever]匹配 “ whatever”中的字符以外的所有字符,因此可以正常工作:

a_string.gsub /[^0-9,-]/, ''

Note that the hyphen has to come last, as otherwise it will be interpreted as a range indicator. 请注意,连字符必须排在最后,否则它将被解释为范围指示符。

To demonstrate, I put all your "before" strings into an Array and used Enumerable#map to run the above gsub call on all of them, producing an Array of the "after" strings: 为了演示,我将所有“ before”字符串放入一个数组中,并使用Enumerable#map对所有这些字符串运行上述gsub调用,生成了“ after”字符串的数组:

["!1,2e,3,6..-10", "ffff5-10....", "1.2,15"].map { |s| s.gsub /[^0-9,-]/, '' }

# => ["1,2,3,6-10", "5-10", "12,15"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM