views:

142

answers:

3

I want regular expression for HH:MM:SS AM/PM here HH must be 1-12 only, MM must 60 min, SS as usual (60 sec.) I any have it properly ...?

+4  A: 
/^([1-9]|10|11|12):[0-5][0-9]:[0-5][0-9] [AP]M$/
Mark Byers
Elegant! +1 for brevity.
Carl Smotricz
Doesnt support the HH notation given in the question, altho he also follows that with "HH must be 1-12" so who knows. Also might want to add a case for leap seconds, as rare as they are.
mynameiscoffey
It can certainly be made shorter: /^([1-9]|1[0-2])(:[0-5][0-9]){2} [AP]M$/ but I think it makes it harder to read. ;)
Mark Byers
@mynameiscoffey: Regarding your point about HH, I've already asked about that as a comment to the question. Regarding your point about leap seconds, I'd say that it depends whether it is user input in a GUI or parsing a protocol. For user input, entry of :60 as seconds is more likely to be a mistake than an intentional entry, and my reading of the question is that he does not want to include :60 in the match (although that may have been an oversight).
Mark Byers
Completely agree, just figured since the OP has not responded to your question I figured it might be helpful to him to have as much information about the various versions popping around here, and agree that if this is for user input validation that leap seconds would be a silly thing to include as it is completely unnecessary but required if its an automated feed.
mynameiscoffey
very nice regexp string!
jspcal
+5  A: 
(0[1-9]|1[0-2]):([0-5][0-9]:[0-5][0-9]|(59|44|29):60) (AM|am|PM|pm)
jspcal
+1 for leap seconds. You missed the AM/PM, but that's easy enough.
Chris Thompson
Leap seconds happen in both AM and PM depending on your time zone (if you are +GMT it happens in the AM).
mynameiscoffey
only need am/pm in small case Currect it:(0[1-9]|1[0-2]):([0-5][0-9]):([0-5][0-9]|60) (AM|PM|am|pm)
Lalit
+2  A: 

If you want to be able to have the zero padding as optional as well as leap seconds:

/^((0?[1-9])|(1[0-2])):[0-5]\d:(([0-5]\d)|(60)) [AP]M$/

The breakdown:
(0?[1-9]|1[0-2]) 1-9 (with optional leading zero) or 10-12
[0-5][0-9] 00-59 (0-5 for first digit, 0-9 for second)
([0-5][0-9])|(60) Leap seconds
[AP]M AM/PM

mynameiscoffey
Updated, thanks for the catch - that's what I get for not testing it first.
mynameiscoffey
very nice regexp!
jspcal