hmaxx
hmaxx

Reputation: 657

regex match hh:mm:ss optional hours

I have /^(?:1[0-2]|0[0-9]):[0-5][0-9]:[0-5][0-9]$/ pattern which works in PHP but when I tried to use it in Js, it doesn't work. I want to match only two formats with mandatory leading zeros: 00:00:00 or 00:00

Upvotes: 0

Views: 854

Answers (3)

LukStorms
LukStorms

Reputation: 29647

To also match 00:00 then i assume the first part with the hours must be made optional.

This regex will also put the hour/minute/second into the capture groups $1 $2 $3.

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

Test snippet:

const reg = /^(?:(1[0-2]|0[0-9])[:])?([0-5][0-9])[:]([0-5][0-9])$/;

strings = ["00:00:00","00:00","12:01","24:59","59:59","12:59:59",
           "14:15:16","00:60","60:00","0:0:0"]

for (const s of strings) {
   console.log(s+" : "+reg.test(s));
}
   

For a 24 hour notation "00:00:00" till "23:59:59" & "00:00" till "59:59", the pattern below can be used

^(?:([01][0-9]|2[0-3])[:])?([0-5][0-9])[:]([0-5][0-9])$

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520978

If you want optional hours, then just make the hours component of your pattern optional:

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

console.log(/^(?:(?:1[0-2]|0[0-9]):)?[0-5][0-9]:[0-5][0-9]$/.test("10:00:00"));
console.log(/^(?:(?:1[0-2]|0[0-9]):)?[0-5][0-9]:[0-5][0-9]$/.test("00:00"));

Upvotes: 0

Barmar
Barmar

Reputation: 780798

You need to make the group containing the hours optional by putting ? after it, and also put the colon following it into the group.

console.log(/^(?:1[0-2]|0[0-9]:)?[0-5][0-9]:[0-5][0-9]$/.test("00:00:00"));
console.log(/^(?:1[0-2]|0[0-9]:)?[0-5][0-9]:[0-5][0-9]$/.test("00:00"));

I'll bet you had this in the PHP version, since that seems like the only reason to have the non-capturing group in the first place. You probably just missed it when copying to Javascript.

Upvotes: 1

Related Questions