Last active
August 29, 2015 13:57
-
-
Save nisar1/9572731 to your computer and use it in GitHub Desktop.
validate traditional time formats regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Hours and minutes, 12-hour clock: | |
┌──────────────────────────────────────────────┐ | |
│ ^(1[0-2]|0?[1-9]):([0-5]?[0-9])(●?[AP]M)?$ │ | |
└──────────────────────────────────────────────┘ | |
Hours and minutes, 24-hour clock: | |
┌──────────────────────────────────────────────┐ | |
│ ^(2[0-3]|[01]?[0-9]):([0-5]?[0-9])$ │ | |
└──────────────────────────────────────────────┘ | |
Hours, minutes, and seconds, 12-hour clock: | |
┌──────────────────────────────────────────────────────────────┐ | |
│ ^(1[0-2]|0?[1-9]):([0-5]?[0-9]):([0-5]?[0-9])(●?[AP]M)?$ │ | |
└──────────────────────────────────────────────────────────────┘ | |
Hours, minutes, and seconds, 24-hour clock: | |
┌──────────────────────────────────────────────────────────────┐ | |
│ ^(2[0-3]|[01]?[0-9]):([0-5]?[0-9]):([0-5]?[0-9])$ │ | |
└──────────────────────────────────────────────────────────────┘ | |
variation | |
---------- | |
► Merely removing the anchors from the regular expression is not the | |
right solution. That would allow the hour and minute regexes to | |
match 12:12 within 9912:1299, for instance. Instead of anchoring | |
the regex match to the start and end of the subject, | |
example: | |
┌──────────────────────────────────────────────┐ | |
│ \b(2[0-3]|[01]?[0-9]):([0-5]?[0-9])\b │ | |
└──────────────────────────────────────────────┘ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment