create regex to match format of 00:00:00 for duration (not time)
Asked Answered
Z

2

6

Hi i'm using laravel and I want to validate create a regex which will allow a specific format for duration (not time as this can exceed a 24 hr format). so for example 124hrs 30 mins and 24 secs would be represented as follows 124:30:24. But the first value can be over 1 character and a number, the second value needs be a colon, the third value needs to be 2 characters and a number, the fourth value needs to be a colon and the fifth value needs to be 2 characters and a numbers.

Any ideas how I can create an regex that will achieve this to insert into the following array?

$rules = array(
  'duration'          => 'required|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/'
);

invalid examples:

alphacharacters e.g. qwerty
0:0:0
0:
0
1
30:211:211
30:2111:2111
a:d:d
asd

valid examples:

01:00:00
1:00:00
30:21:21
330:21:21
1330:21:21
11330:21:21
basically any amount of hours.
Zealous answered 21/11, 2015 at 22:50 Comment(2)
could you add some example that are valid and not valid please?Rawinsonde
@LouisBarranqueiro have doneZealous
L
8

Give your examples this regex should suffice:

^\d+:\d{2}:\d{2}$

Demo: https://regex101.com/r/kO4xN2/2

\d is a number
+ is a quantifier meaning one or more of the preceding character (or group)
{} is an amount of characters to allow (you can give it a range as well)
^$ are anchors, so the string must be an exact match, if there is more content in the string this should be removed.

Limassol answered 21/11, 2015 at 22:58 Comment(0)
J
0

in case fractions are allowable (ex: 11330:21:21.123)

^\d+:\d{2}:\d{2}(\.\d+)?$

https://regex101.com/r/AGzROR/1

Jalapa answered 2/10, 2024 at 15:20 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.