Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for time in hh:mm am/pm format

Tags:

regex

I need to make strict validation of input for a school project, time in format HH:MM am/pm. So far i've got this RegEx expression:

(([01]?[0-9]):([0-5][0-9]) ([AaPp][Mm]))

here's a working demo: http://regexr.com/3c9b5

The only problem is that it accepts times 13:00 to 19:59

What is the correct regular expresion? RegEx has always been hard for me

like image 774
TianRB Avatar asked Nov 24 '15 23:11

TianRB


3 Answers

You can use:

\b((1[0-2]|0?[1-9]):([0-5][0-9]) ([AaPp][Mm]))
EDIT:         ^ changed this from "0" to "1" to not accept 00:00
like image 199
R Nar Avatar answered Sep 19 '22 12:09

R Nar


  ([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])\s*([AaPp][Mm])

For the following:

10:00AM

10:00PM

10:00am

10:00pm

10:00 pm

10:00 am

10:30PM

23:46am

like image 36
Danny M Avatar answered Sep 19 '22 12:09

Danny M


You can use this:

^([1-9]|0[1-9]|1[0-2]):[0-5][0-9] ([AaPp][Mm])$

It will accept 1:00 am, 01:00 AM, 12:00 PM, 11:00 pm, 12:59 Pm. But won't accept 00:00 am or 00:00 PM or 01:60 Am.

like image 26
Tejas Hirpara Avatar answered Sep 21 '22 12:09

Tejas Hirpara