[英]Date String not matching in Scala
I used this to define a function that returns 0 if a string matches a pattern, 0 otherwise: 我使用它来定义一个函数,如果字符串匹配模式,则返回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
}
}
When I execute: 当我执行:
verif("2019-07-01 00:00:00.000000000") // Returns 1
I verified my regex on multiple online testors ( here or here ) and it is working. 我在多个在线测试器( 这里或这里 )验证了我的正则表达式,它正在工作。
You defined 3 capturing groups, hence you must pattern match three groups. 您定义了3个捕获组,因此必须模式匹配三个组。 However, it makes sense to just use non-capturing groups and the code like:
但是,仅使用非捕获组和代码是有意义的:
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
See the Scala demo 请参阅Scala演示
Note you also need to escape the dot to match a literal dot. 请注意,您还需要转义点以匹配文字点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.