[英]how to get numbers from array of strings?
我有这个字符串数组。
["Anyvalue", "Total", "value:", "9,999.00", "Token", " ", "|", " ", "Total", "chain", "value:", "4,948"]
我正在尝试在一行代码中获取数字。 我尝试了很多方法,但并没有像预期的那样真正有用。
我使用的是 grep 方法:
array.grep(/\d+/, &:to_i) #[9, 4]
但它只返回一个由第一个整数组成的数组。 似乎我必须在模式中添加一些东西,但我不知道是什么。
或者还有另一种方法可以在数组中获取这些数字?
您可以使用:
array.grep(/[\d,]+\.?\d+/)
如果你想要int
:
array.grep(/[\d,]+\.?\d+/).map {_1.gsub(/[^0-9\.]/, '').to_i}
和更快的方法(大约 5X 到 10X):
array.grep(/[\d,]+\.?\d+/).map { _1.delete("^0-9.").to_i }
arr = ["Anyvalue", "Total", "value:", "9,999.00", "Token", " ", "61.4.5",
"|", "chain", "-4,948", "3,25.61", "1,234,567.899"]
rgx = /\A\-?\d{1,3}(?:,\d{3})*(?:\.\d+)?\z/
arr.grep(rgx)
#=> ["9,999.00", "-4,948", "1,234,567.899"]
正则表达式演示。 在链接中,正则表达式是使用 PCRE 正则表达式引擎评估的,但使用 Ruby 的 Onigmo 引擎时结果是相同的。 此外,在链接中,我使用了锚点^
和$
(行首和行尾)而不是\A
和\z
(字符串的开头和结尾),以便针对多个字符串测试正则表达式。
正则表达式可以分解如下。
/
\A # match the beginning of the string
\-? # optionally match '-'
\d{1,3} # match between 1 and 3 digits inclusively
(?: # begin a non-capture group
,\d{3} # match a comma followed by 3 digits
)* # end the non-capture group and execute 0 or more times
(?: # begin a non-capture group
\.\d+ # match a period followed by one or more digits
)? # end the non-capture and make it optional
\z # match the end of the string
/
为了使测试更加健壮,我们可以使用方法Kernel::Float , Kernel::Rational和Kernel::Complex设置为false
的所有可选参数:exception
arr = ["Total", "9,999.00", " ", "61.4.5", "23e4", "-234.7e-2", "1+2i",
"3/4", "|", "chain", "-4,948", "3,25.61", "1,234,567.899", "10"]
arr.select { |s| s.match?(rxg) || Float(s, exception: false) ||
Rational(s, exception: false) Complex(s, exception: false) }
#=> ["9,999.00", "23e4", "-234.7e-2", "1+2i", "3/4", "-4,948",
# "1,234,567.899", "10"]
请注意, "23e4"
、 "-234.7e-2"
、 "1+2i"
和"3/4"
分别是 integer、浮点数、复数和有理数的字符串表示形式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.