我这里有这个正则表达式:
^(\d{1,2}):(\d{2})(:00)?(\s)?(AM|PM|am|pm)?$
它做得很好。允许诸如 23:00:00
或 12:00 AM
或 1: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/