【问题标题】:Date String not matching in ScalaScala中的日期字符串不匹配
【发布时间】:2019-12-30 20:00:59
【问题描述】:

我使用this 定义了一个函数,如果字符串匹配某个模式,则返回 0,否则返回 0:

def verif (s:String): Int = {
 val p = """[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) (2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9].[0-9]{9}""".r
 s match {
 case p(item) => 0  
 case _ => 1
 }
}

当我执行时:

verif("2019-07-01 00:00:00.000000000") // Returns 1

我在多个在线测试人员(herehere)上验证了我的正则表达式,它正在工作。

【问题讨论】:

    标签: scala pattern-matching case


    【解决方案1】:

    您定义了 3 个捕获组,因此您必须对三个组进行模式匹配。但是,只使用 non-capturing 组和如下代码是有意义的:

    def verif (s:String): Int = {
      val p = """[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1]) (?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]\.[0-9]{9}""".r
      s match {
        case p() => 0  
        case _ => 1
      }
    }
    println(verif("2019-07-01 00:00:00.000000000"))   // => 0
    

    Scala demo

    请注意,您还需要转义点以匹配文字点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      • 2016-01-08
      • 1970-01-01
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多