Regular expression hh:mm:ss:nnn

1711 views regex
0

i have had a go at matching a regular expression that is given in hh:mm:ss:nnn

with the range being :

00:00:00:000 for lowest 
23:59:59:999 as the highest

a valid example is 06:07:22:575 
invalid example being 6:7:22:475 

so far i have given it a go and hasnt worked with this :

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

but it hasnt worked.. can someone help me out

answered question

3 Answers

7

Try this regex:

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

The only possibly tricky part here which might require explanation is the portion of the regex which covers the first two digits. In this case, we only want to support numbers from 0 to 23 inclusive. So, we use this pattern:

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

This says to match (and not capture) either a 0 or 1 followed by 0 to 9, i.e. 00-19, or a 2 followed by 0 to 3, i.e. 20-23.

Here is a working demo:

Demo

posted this
2

I think you just missed some square and round brackets?

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

When you are trying to use check number between 00 and 59, it should be

( (0[1-9])|([1-5][0-9]) )

The one you tried (0[1-9])|(1-5[0-9] will only fetch 01~09

posted this
10

I would recommend:
/^[0-1][0-9]:[0-6][0-9]:[0-6][0-9]:[0-9][0-9][0-9]|^2[1-3]:[0-6][0-9]:[0-6][0-9]:[0-9][0-9][0-9]$/

Comprising two parts:

^[0-1][0-9]:[0-6][0-9]:[0-6][0-9]:[0-9][0-9][0-9]
^2[1-3]:[0-6][0-9]:[0-6][0-9]:[0-9][0-9][0-9]

This will match any time under 24 hours in the format listed above.

This can be seen working on Regex101 here.

const regex = /^[0-1][0-9]:[0-6][0-9]:[0-6][0-9]:[0-9][0-9][0-9]|^2[1-3]:[0-6][0-9]:[0-6][0-9]:[0-9][0-9][0-9]$/gm;

const strings = [
  "00:00:00:000",
  "23:59:59:999",
  "06:07:22:575",
  "6:7:22:475"
]

for (let i = 0; i < strings.length; i++) {
  console.log(regex.test(strings[i]));
}

posted this

Have an answer?

JD

Please login first before posting an answer.