I used this to define a function that returns 0 if a string matches a pattern, 0 otherwise:
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. 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
Note you also need to escape the dot to match a literal dot.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.