Skip to content

Instantly share code, notes, and snippets.

@nisar1
Last active August 29, 2015 13:57
Show Gist options
  • Save nisar1/9572731 to your computer and use it in GitHub Desktop.
Save nisar1/9572731 to your computer and use it in GitHub Desktop.
validate traditional time formats regex
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