时间格式验证正则表达式,军事或 AM/PM 但不是两者
Time format validation regex, either military or AM/PM but not both
我这里有这个正则表达式:
^(\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
$
这是我解决问题的尝试:
^((0?[0-9]|1[0-2]):([0-5][0-9])(?::([0-5][0-9]))?)\s?([ap]m)?|([0-1][0-9]|[2][0-3]):([0-5][0-9])(?::([0-5][0-9]))?$
JS:
var re = /^((0?[0-9]|1[0-2]):([0-5][0-9])(?::([0-5][0-9]))?)\s?([ap]m)?|([0-1][0-9]|[2][0-3]):([0-5][0-9])(?::([0-5][0-9]))?$/gmi;
见demo
注意使用 i
选项(启用不区分大小写的匹配)和 m
来匹配整行。
此正则表达式允许分钟和秒(秒是可选的)。
我这里有这个正则表达式:
^(\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
$
这是我解决问题的尝试:
^((0?[0-9]|1[0-2]):([0-5][0-9])(?::([0-5][0-9]))?)\s?([ap]m)?|([0-1][0-9]|[2][0-3]):([0-5][0-9])(?::([0-5][0-9]))?$
JS:
var re = /^((0?[0-9]|1[0-2]):([0-5][0-9])(?::([0-5][0-9]))?)\s?([ap]m)?|([0-1][0-9]|[2][0-3]):([0-5][0-9])(?::([0-5][0-9]))?$/gmi;
见demo
注意使用 i
选项(启用不区分大小写的匹配)和 m
来匹配整行。
此正则表达式允许分钟和秒(秒是可选的)。