abipc
abipc

Reputation: 1035

Scala Pattern Match

I am using this pattern match from regexlib.com -

^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$

This seems to be working fine =>

val RE = """^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$""".r
RE.findAllMatchIn("31/12/2003 11:59:59 PM").foreach(println) //prints 31/12/2003 11:59:59 PM
RE.findAllMatchIn("31/122003 11:59:59 PM").foreach(println) //prints nothing

However, I am not able to match it directly like this -

"31/12/2003 11:59:59 PM" match {
    case RE(_) => println("Yes")
    case _ => println("No")
}

This prints "No". I am expecting "Yes"

Upvotes: 3

Views: 117

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

It is due to the capturing groups that you have several in the pattern. You need to use RE(_*) in the first case to just check if a string matches without extracting capturing groups:

val RE = """^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$""".r
    "31/12/2003 11:59:59 PM" match {
        case RE(_*) => println("Yes")
        case _ => println("No")
    }

See the Scala demo

Upvotes: 3

Related Questions