Developer Developer - 1 year ago 86
Perl Question

Regex to get time in hour minutes and seconds

I am getting a time in this format


Now I want to get the time in like
13Hour 26Min and 23Seconds

How can we do this in Perl through a regular expression? I was trying this but I am unable to do this

$line =~ /^.+?\:(.+)/

Please help me in this how we can do this.

Answer Source

There is a number of most excellent date-time modules, but given the unusual output format and simple input perhaps a regex is a good solution here.

my ($day, $mon, $year, $hour, $minute, $sec) = 
    $line =~ m|(\d+)/([^/]+)/(\d{4}):(\d{2}):(\d{2}):(\d{2})|;

Now print them out as you please.

What you seemed to try is

my @hms = $line =~ m/:(\d+)/g;
print "@hms\n";

With the string from the question this prints 13 26 23. This captures all consecutive digits following a colon, repeatedly by the /g modifier. So @hms contains: hour, minute, second.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download