使用正则来判断:
scala> val regex="""^\d+$""".r
regex: scala.util.matching.Regex = ^\d+$
scala> val test = Array("123","abc")
test: Array[String] = Array(123, abc)
scala> test.filter(regex.findFirstMatchIn(_) != None)
res57: Array[String] = Array(123)
另一个例子:
scala> val regex="""^\d+$""".r
regex: scala.util.matching.Regex = ^\d+$
scala> val ss = "1#a\n2#b\n3#c\nxx#yy\nabc"
ss: String =
1#a
2#b
3#c
xx#yy
abc
scala> val maps = ss.split("\n").map(a => a.split("#")).filter((b:Array[String]) => b.size==2 && regex.findFirstMatchIn(b(0)) != None).map(_ match { case Array(a,b) => (a.toInt ->b)}).toMap[Int,String]
maps: scala.collection.immutable.Map[Int,String] = Map(1 -> a, 2 -> b, 3 -> c)
scala> maps(2)
res61: String = b