2017-10-07 172 views
3

我使用從regexlib.com這個模式匹配 -Scala的模式匹配

^(?=\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})?$ 

這似乎是做工精細=>

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 

不過,我不能夠匹配它直接像這 -

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

這打印「否」。我期待「是」

+1

我想,我的眼睛被永久由此受損。我怎麼能看不到它? 請不要這樣做給人。只要使用'DateFormat' – Dima

+0

同意。我沒有在生產中使用它。 – abipc

回答

3

這是由於捕獲組,你有幾個模式。您需要使用RE(_*)在第一種情況下,只是檢查是否字符串匹配,而不提取捕獲組:

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") 
    } 

Scala demo