【问题标题】:Improve code with checking element in array is digit通过检查数组中的元素是数字来改进代码
【发布时间】:2019-11-14 05:41:36
【问题描述】:

我想检查 String 中的每个元素是否都是数字。首先,我通过正则表达式 [, ]+ 表达式将字符串拆分为数组,然后尝试通过 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))

【问题讨论】:

  • split 返回的数组永远不会为空。
  • 如果你传递字符串1 2 3, 123应该是什么答案? improve this code 是什么意思?

标签: arrays regex scala


【解决方案1】:

使用要求字符串完全匹配模式的matches

st.matches("""\d+(?:\s*,\s*\d+)*""")

请参阅 Scala demoregex demo

详情

  • 在三引号字符串文字中,不需要双转义反斜杠作为正则表达式转义的一部分
  • 锚点 - ^$ - 当模式与 .matches 一起使用时是隐式的
  • 正则表达式表示1+ 位数字后跟 0 次或多次重复的逗号,其中包含 0 或多个空格,然后是 1+ 位数字

【讨论】:

  • " 1,2,4""1,2,4 " 等字符串返回false。不确定这是否是预期的结果。
  • @jwvh 可以预期,请参阅问题中没有前导/尾随空格的示例输入。无论如何,它可以很容易地在模式的开头和结尾添加\s*
  • 只是好奇:为什么让它不被捕获? ?: 有什么优势?
  • @jwvh 见Are non-capturing groups redundant?。简而言之:最好的做法是仅在需要访问部分正则表达式匹配后才使用捕获组。
【解决方案2】:

我认为它可以被简化,同时也让它更加健壮。

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)

【讨论】:

  • 不错的方法@jwvh
猜你喜欢
  • 1970-01-01
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-30
  • 2022-01-02
相关资源
最近更新 更多