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 ...?
regular expression for time
Asked Answered
Your 'HH' notation implies that the hours must be zero padded and start from 00, yet you contradict this later in your question. What do you actually mean? Can you be a little more precise, perhaps with a few examples of matching and failing strings? –
Coinstantaneous
(0[1-9]|1[0-2]):([0-5][0-9]:[0-5][0-9]|(59|44|29):60) (AM|am|PM|pm)
+1 for leap seconds. You missed the AM/PM, but that's easy enough. –
Nester
Leap seconds happen in both AM and PM depending on your time zone (if you are +GMT it happens in the AM). –
Langbehn
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) –
Shuck
/^([1-9]|10|11|12):[0-5][0-9]:[0-5][0-9] [AP]M$/
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. –
Langbehn
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. ;) –
Coinstantaneous
@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). –
Coinstantaneous
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. –
Langbehn
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
Updated, thanks for the catch - that's what I get for not testing it first. –
Langbehn
© 2022 - 2024 — McMap. All rights reserved.