Extract numbers from String Array

后端 未结 4 404
孤独总比滥情好
孤独总比滥情好 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:54

    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)
    

提交回复
热议问题