Extract numbers from String Array

你。 提交于 2019-12-02 09:25:17

Consider

import scala.util._
tokens.flatMap(s => Try( s.split("\\W+").mkString(".").toDouble ).toOption)

where we tokenize further each array string into words and append them by a dot (this ought to strip out for instance trailing dots); we convert the resulting tokens into doubles whenever possible (note Try toOption will deliver None for failed conversions). With flatMap we keep only successful conversion.

Simply filter your array with regex

val numericRegex: String = "\\d+\\.\\d+"
tokens filter(_.matches(numericRegex))

Note that the 6'th value 232.2. is not a number. you must remove the last dot "." so it will be 232.2

If values include spaces than you have to trim them

tokens map (_.trim) filter (_.matches(numericRegex))
res28: Array[String] = Array(234.2, 8.3)

With Regex, you can use this code to catch all the numbers:

\d+\.?\d+

Demo: https://regex101.com/r/pZomjn/1

In Scala there is a syntactic sugar to compose map and filter called for comprehension. Below is a version of regex approach based on for:

val regex = ".*\\d+\\.?\\d+.*"
val nums = for {
    str <- tokens if str.matches(regex)
    numStr = str.trim.split("\\W+").mkString(".")
} yield numStr.toDouble

It gives the desired output:

nums: Array[Double] = Array(234.2, 8.3)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!