Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.
like image 603
GSG Avatar asked Nov 21 '15 22:11

GSG


1 Answers

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.

like image 110
chris85 Avatar answered Sep 29 '22 14:09

chris85