Will "the Mighty" Strohl

Regular Expression - Validating Time

I am just an amateur when it comes to regular expression, but I plan on getting a whole lot better at it. There is too much potential there to not want to use it more often. I just came up with a regular expression pattern to validate time format. It has some small checks incorporated for valid times, but it is not 100% inclusive. Here is the expression:

^[0-1]?[0-9]{1}:[0-5]{1}[0-9]{1} (AM|PM|am|pm)$

The preceding pattern will match times such as:

12:29 PM, 12:29 pm, 2:14 AM, 2:14 am, etc.

It will not match:

22:29 PM, 11:69 AM, etc.

However, the catch here is that it will also match times like:

19:00 AM, 13:14 pm, etc.

It may or may not be obvious to you that this not a valid time, but the expression will not find it as obvious. Like I said, I am an amateur here, so let me know if you have a better expression for this.



blog comments powered by Disqus