![]() |
VOOZH | about |
In this article, we will explore how to use regex to validate the used time format HH:mm:ss. Regular expressions (regex) offer a method, for validating time formats ensuring that they follow patterns which is mentioned below in the article.
When testing a time string, against this pattern the regular expression engine tries to match each part of the pattern to its part, in the string. If the entire string perfectly matches the pattern, it is considered a time format in HH:mm:ss. If any part of the string does not follow the pattern, it is considered invalid.
^([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$
18:35:40 is a valid time format.
In the above Program we are comparing the String with the mentioned regex. And the regex is explained below:
Matches the hour ->
- ^ Matches the beginning of the string.
- [0-1][0-9] Matches numbers 00 to 19.
- | Signifies "or".
- 2[0-3] Matches numbers 20 to 23.
Matches the minutes ->
- : Matches a literal colon
- [0-5][0-9] Matches numbers 00 to 59
Matches the seconds ->
- : Matches a literal colon.
- [0-5][0-9] Matches numbers 00 to 59.
- $ dollar sign indicates ending of the string.