javascript HH:MM:SS 的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14892740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regular expression for HH:MM:SS
提问by user1646528
I have a reqular expression that matches HH:MM e.g. 12:23 and it is:
我有一个匹配 HH:MM 例如 12:23 的正则表达式,它是:
function IsValidTime(timeString)
{
var pattern = /^\d?\d:\d{2}$/;
if (!timeString.match(pattern))
return false;
}
How do I change this line:
我如何更改此行:
var pattern = /^\d?\d:\d{2}$/;
var 模式 = /^\d?\d:\d{2}$/;
to check for a string that is formatted with seconds like so: HH:MM:SSe.g. 12:23:05
检查以秒为格式的字符串,如下所示:HH:MM:SS例如 12:23:05
回答by Tim Pietzcker
/^(?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]$/
for 24-hour time, leading zeroes mandatory.
对于 24 小时制,必须使用前导零。
/^(?:2[0-3]|[01]?[0-9]):[0-5][0-9]:[0-5][0-9]$/
for 24-hour time, leading zeroes optional.
24 小时制,前导零可选。
/^(?:1[0-2]|0[0-9]):[0-5][0-9]:[0-5][0-9]$/
for 12-hour time, leading zeroes mandatory.
12 小时制,前导零是强制性的。
/^(?:1[0-2]|0?[0-9]):[0-5][0-9]:[0-5][0-9]$/
for 12-hour time, leading zeroes optional.
12 小时制,前导零可选。
回答by h2ooooooo
Something as simple as the following should work:
像下面这样简单的事情应该可以工作:
/([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]/g
Regex Explanation:
正则表达式说明:
([01][0-9]|2[0-3])
- A collection of the following:
[01][0-9]
the characters "0" or "1" followed by any digit between 0 and 9|
- or2[0-3]
the character "2" followed by a digit between 0 and 3
:
a literal colon[0-5][0-9]
- any digit between 0 to 5 followed by any digit between 0 and 9:
a literal colon[0-5][0-9]
- any digit between 0 to 5 followed by any digit between 0 and 9
([01][0-9]|2[0-3])
- 以下内容的集合:
[01][0-9]
字符“0”或“1”后跟 0 到 9 之间的任何数字|
-或2[0-3]
字符“2”后跟一个 0 到 3 之间的数字
:
字面冒号[0-5][0-9]
- 0 到 5 之间的任何数字后跟 0 到 9 之间的任何数字:
字面冒号[0-5][0-9]
- 0 到 5 之间的任何数字后跟 0 到 9 之间的任何数字
Demo:
演示:
回答by Christoph
Basing on your regex for detecting 99:99:99
, the following regex would suffice:
根据您用于检测99:99:99
的正则表达式,以下正则表达式就足够了:
/^\d?\d:\d{2}:\d{2}$/
or a bit more sophisticated
或者更复杂一点
/^\d?\d(?::\d{2}){2}$/
but much better would be (because it correctly matches the ranges):
但会更好(因为它正确匹配范围):
/^(?:[01]?\d|2[0-3]):[0-5]\d:[0-5]\d$/
which would conform the function name IsValidTime
...
这将符合函数名称IsValidTime
...
回答by sourcecode
Validate time in format as“ hh:mm am/pm ” in javascript
在javascript中以“hh:mm am/pm”格式验证时间
function timeValidation(strTime) {
var timeFormat = /^(?:1[0-2]|0?[0-9]):[0-5][0-9]\s?(?:am|pm)?/;
return timeFormat.test(strTime);
}
timeValidation("12:30 PM") // return true
timeValidation("12:30 PM") // 返回真
timeValidation("12:30 ") // return false
timeValidation("12:30 ") // 返回 false
timeValidation("27:30 AM") // return false
timeValidation("27:30 AM") // 返回 false