字符串 "hh:mm:ss tt" 的正则表达式

Regex for string "hh:mm:ss tt"

如何限制字符串具有以下值之一?全部不区分大小写:

  1. 时:分:
  2. 时:分:秒
  3. hh:mm tt
  4. hh:mm:ss tt

我试过这个正则表达式 ^[hh:mm][:ss]?[ tt]?[:ss tt]?$,但它没有给我想要的结果。有帮助吗?

我认为你混淆了字符 class[ab] 和组 (abc)
试试这个正则表达式:

^(hh:mm)(?::ss)?(?: tt)?$

其中:

^           : begining of string
  (hh:mm)   : capture group that contains 'hh:mm'
  (?::ss)?  : optional non capture group that contains ':ss'
  (?: tt)?  : optional non capture group that contains ' tt'
$           : end of string