如何安全转换字符串并从中提取整数并返回集合



我有一组看起来像:

的字符串
"user-123"
"user-498"
"user-9891"

我想返回这样的整数:

123
498
9891

我可以做到这一点:

val mySet = // ....
mySet.map(x => x.replace("user-").toInt)

但是,如果TOINT解析失败,它将崩溃,这将是一种更安全的方法?

忽略失败的字符串:

mySet.flatMap(s => Try(s.replace("user-", "").toInt).toOption)

使用isDigit()

Try("user-1234".toCharArray.filter(_.isDigit) .foldLeft("")((a, b) => a + b).toInt) .getOrElse(0)

您可以使用简单的正则表达式仅保留数值。

类似的东西:

val mySet = Seq("user-123","user-498","user-9891")
mySet.map(_.replaceAll("[^\d]", ""))

您可以检查将成功转换为Int的字符串:

mySet.map(_.stripPrefix("user-")).collect { case x if x.forall(_.isDigit) => x.toInt }

最新更新