首页 > 解决方案 > RegEx to check 24 hours time format fails

问题描述

I have the following RegEx that is supposed to do 24 hours time format validation, which I'm trying out in https://rubular.com

/^[0-23]{2}:[0-59]{2}:[0-59]{2}$/

But the following times fails to match even if they look correct

02:06:00
04:05:00

Why this is so?

标签: regex

解决方案


In character classes, you're supposed to denote the range of characters allowed (in contrast to the numbers you want to match in your example). For minutes and seconds, this is relatively straight-forward - the following expression

[0-5][0-9]

...will match any numerical string from "00" to "59".

But for the hours, you need to two separate expressions:

[01][0-9]|2[0-3]

...one to match "00" to "19" and one to match "20" to "23". Due to the alternative used (| character), these need to be grouped, which adds another bit of syntax (?:...). Finally we're just adding the anchors ^ and $ for beginning and end of string, which you already had where they belong.

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

You can check this solution out at regex101, if you like.


推荐阅读