Regular expression to validate clock time

To validate time from 00:00 to 11:59 you can use a simple regex.

The regex is (?:0[0-9]|1[0-1]):[0-5][0-9]
It means if the first digit of hour is 0, then second digit can be any one from 0-9.
Otherwise if the first digit is 1, that case second digit can only be 1 or 2.

For minute section, first digit can be only from 0-5, and second digit can be from 0-9.

I'm giving you the example using a perl code, but the regex will work with any PCRE compatible engine.

Using Perl

my $time = "01:19";
if($time =~ /(?:0[0-9]|1[0-1]):[0-5][0-9]/){
print "the time is valid\n";
}
else{
print "the time is not valid\n";
}


Simple task, but yet too hard if you don't this :-)

Comments

Anonymous said…
That's very helpful.