我要检查字符串中的每个元素是否为数字。首先,我通过regexp [, ]+表达式将字符串拆分为数组,然后尝试通过forall和isDigit检查每个元素。
object Test extends App {
val st = "1, 434, 634, 8"
st.split("[ ,]+") match {
case arr if !arr.forall(_.forall(_.isDigit)) => println("not an array")
case arr if arr.isEmpty => println("bad delimiter")
case _ => println("success")
}
}如何改进这段代码和!arr.forall(_.forall(_.isDigit))
发布于 2019-11-14 08:04:36
发布于 2019-11-14 05:58:02
我认为它可以简化,同时也使它更加健壮。
val st = "1,434 , 634 , 8" //a little messier but still valid
st.split(",").forall(" *\\d+ *".r.matches) //res0: Boolean = true我认为像"1,,,434 , 634 2 , "这样的字符串应该会失败。
正则表达式可以放在一个变量中,以便只编译一次。
val digits = " *\\d+ *".r
st.split(",").forall(digits.matches)https://stackoverflow.com/questions/58850085
复制相似问题