javascript - 时间格式验证正则表达式,军事或 AM/PM,但不能两者兼而有之

标签 javascript regex time-format

我这里有这个正则表达式:

^(\d{1,2}):(\d{2})(:00)?(\s)?(AM|PM|am|pm)?$

它做得很好。允许诸如 23:00:0012:00 AM1:00am 等内容。

问题是它还允许诸如 23:24 AM 之类的内容。

如果第一组数字 > 12,修改此值或附加此值以禁止 AM/PM 的最佳方法是什么?

最佳答案

尝试一下:

^(?:(?:(?:0?\d|1[012]):[0-5]\d(?::00)? ?[ap]m)|(?:[01]?\d|2[0-3]):[0-5]\d(?::00)?)$

说明:

^
(?:                 : start non capturing group
  (?:               : start non capturing group
    (?:             : start non capturing group
      0?\d          : matches optional 0 followed by 1 digit
      |             : OR
      1[012]        : 1 followed by digit between 0 and 2
    )               : end group
    :               : literally :
    [0-5]\d         : digit between 0 and 5 followed by any digit
    (?::00)?        : optional 00 seconds
     ?              : optional space
    [ap]m           : am or pm
  )                 : end group 
  |                 : OR
  (?:               : start non capturing group
   [01]?\d          : 0 or 1 (optional) followed by any digit
   |                : OR
   2[0-3]           : 20 to 23
  )                 : end group
  :                 : literally :
  [0-5]\d           : digit between 0 and 5 followed by any digit
  (?::00)?          : optional 00 seconds
)                   : end group
$                   

关于javascript - 时间格式验证正则表达式,军事或 AM/PM,但不能两者兼而有之,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29963553/

相关文章:

javascript - 多个条件的单一正则表达式模式

regex - JSON 数字正则表达式

java - SimpleDateFormat.getTimeInstance 忽略 24 小时格式

javascript - Dayjs:无法将自定义 24 小时时间格式化为 12 小时

javascript - 开源 Linux Acrobat Javascript 编辑器

javascript - 如何使用jquery获取div值?

javascript - 无法让我的数据绑定(bind)与 knockoutJS 一起工作

Java正则表达式匹配相同特定字符序列之间的所有内容

Javascript:将 24 小时时间字符串转换为 12 小时时间(带 AM/PM,无时区)

javascript - "[Error] ReferenceError: Can' t 查找变量 : data"when trying to get JSON data with AJAX/jQuery request