Extract numbers from String Array

后端 未结 4 406
孤独总比滥情好
孤独总比滥情好 2021-01-24 03:18

I have a Array of Strings

scala> tokens
res34: Array[String] = Array(The, value, of, your, profile, is, 234.2., You, have, potential, to, gain, 8.3, more.)
         


        
4条回答
  •  长情又很酷
    2021-01-24 03:44

    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)
    

提交回复
热议问题