HTML 5 的 24 小时时间正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14772142/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 05:30:06  来源:igfitidea点击:

24 hour time regex for HTML 5

regexhtml

提问by Abdul Ali

Wanted to Inquire about the possible Regex expression for 24-hour time format in HTML 5 (HH:MM) .

想在 HTML 5 (HH:MM) 中查询可能的 24 小时时间格式的 Regex 表达式。

if possible, kindly tell the regex that can be used in the Pattern attribute of HTML 5

如果可能,请告诉可以在 HTML 5 的 Pattern 属性中使用的正则表达式

The time is expected to be in 24-hour format (HH not more than 23).

时间预计为 24 小时制(HH 不超过 23)。

Kind regards,

亲切的问候,

回答by radu florescu

I think this is a possible approach :

我认为这是一种可能的方法:

<input type="text" pattern="([01]?[0-9]|2[0-3]):[0-5][0-9]" id="24h"/>
<input type="text" pattern="([01]?[0-9]{1}|2[0-3]{1}):[0-5]{1}[0-9]{1}" id="24h"/>

http://www.mkyong.com/regular-expressions/how-to-validate-time-in-24-hours-format-with-regular-expression/

http://www.mkyong.com/regular-expressions/how-to-validate-time-in-24-hours-format-with-regular-expression/

([01]?[0-9]|2[0-3]):[0-5][0-9]

Check out this jsfiddle : example

看看这个jsfiddle:例子

回答by pwolaq

Here is the code:

这是代码:

<input type="text" pattern="[0-2]{1}[0-9]{1}:[0-5]{1}[0-9]{1}" />

it does allow invalid hour values: 24,25,26,27,28,29, if you want to be extra correct you can do it that way:

它确实允许无效的小时值:24,25,26,27,28,29,如果你想更加正确,你可以这样做:

<input type="text" pattern="([0-1]{1}[0-9]{1}|20|21|22|23):[0-5]{1}[0-9]{1}" />

回答by SKS

A bit shorter regex:

更短的正则表达式:

(?:[01]|2(?![4-9])){1}\d{1}:[0-5]{1}\d{1}

So in complete:

所以完整的:

<input type="text" pattern="(?:[01]|2(?![4-9])){1}\d{1}:[0-5]{1}\d{1}" />

In the first non-capturing group ("(?:)") we match exactly one digit, either 0, 1 or 2 not followed by 4-9 (negative lookahead "(?!)"). Then me match one more digit, since it could be any of 0-9 we can go with \d shortcut. Then we match separator ":". Then one digit between 0-5 and one more between 0-9 (again with "\d"). If for some reason you need to match 24 hours as well (sometimes you do), then just adjust negative lookahead, e. g. "(?![5-9])".

在第一个非捕获组 ("(?:)") 中,我们只匹配一个数字,即 0、1 或 2,后面不跟 4-9(负前瞻“(?!)”)。然后我再匹配一位数字,因为它可以是 0-9 中的任何一个,我们可以使用 \d 快捷方式。然后我们匹配分隔符“:”。然后是 0-5 之间的一位数和 0-9 之间的一位数(再次使用“\d”)。如果由于某种原因你也需要匹配 24 小时(有时你需要),那么只需调整负前瞻,例如“(?![5-9])”。

回答by Eduardo Vazquez

If you want to force to have the format HH:MM(e.g. 00:00, 23:59)

如果您想强制使用HH:MM格式(例如 00 :00、23:59)

Then, you could use something like this:

然后,你可以使用这样的东西:

/^([0-1]\d|20|21|22|23):[0-5]\d$/