user3241846
user3241846

Reputation: 677

Changing time format using regex in perl

I want to read 12h format time from file and replace it with 24 hour

example

this is due at 3:15am -> this is due 15:15

I tried saving variables in regex and manupilate it later but didnt work, I also tried using substitution "/s" but because it is variable I couldnt figure it out

Here is my code:

while (<>) {
            my $line = $_;
        print ("this is text before: $line \n");
        if ($line =~ m/\d:\d{2}pm/g){
            print "It is PM! \n";}
        elsif ($line =~ m/(\d):(\d\d)am/g){
                print "this is try: $line \n";
            print "Its AM! \n";}
            $line =~ s/($regexp)/<French>$lexicon{$1}<\/French>/g;
            print "sample after : $line\n";
}

Upvotes: 1

Views: 230

Answers (3)

nu11p01n73R
nu11p01n73R

Reputation: 26667

A simple script can do the work for you

$str="this is due at 3:15pm";
$str=~m/\D+(\d+):\d+(.*)$/;

$hour=($2 eq "am")? ( ($1 == 12 )? 0 : $1 ) : ($1 == 12 ) ? $1 :$1+12;
$min=$2;

$str=~s/at.*/$hour:$min/g;
print "$str\n";

Gives output as

 this is due 15:15

What it does??

  • $str=~m/\D+(\d+):(\d+)(.*)$/; Tries to match the string with the regex

    • \D+ matches anything other than digits. Here it matches this is due at

    • (\d+) matches any number of digits. Here it matches 3. Captured in group 1 , $1 which is the hours

    • : matches :

    • (\d+) matches any number of digits. Here it matches 15, which is the minutes

    • (.*) matches anything follwed, here am . Captures in group 2, `$2

    • $ anchors the regex at end of

  • $hour=($2 eq "am")? ( ($1 == 12 )? 0 : $1 ) : ($1 == 12 ) ? $1 :$1+12; Converts to 24 hour clock. If $2 is pm adds 12 unless it is 12. Also if the time is am and 12 then the hour is 0

  • $str=~s/at.*/$hour:$min/g; substitutes anything from at to end of string with $hour:$min, which is the time obtained from the ternary operation performed before

Upvotes: 2

mkHun
mkHun

Reputation: 5927

Try this it give what you expect

my @data = <DATA>;
foreach my $sm(@data){
if($sm =~/(12)\.\d+(pm)/g){
    print "$&\n";
}
elsif($sm =~m/(\d+(\.)?\d+)(pm)/g )
{
print $1+12,"\n";
}
}

__DATA__
Time 3.15am
Time 3.16pm
Time 5.17pm
Time 1.11am
Time 1.01pm
Time 12.11pm

Upvotes: 0

ssr1012
ssr1012

Reputation: 2589

#!/usr/bin/env perl
use strict;
use warnings;

my $values = time_12h_to_24h("11:00 PM");

sub time_12h_to_24h
{
    my($t12) = @_;
    my($hh,$mm,$ampm) = $t12 =~ m/^(\d\d?):(\d\d?)\s*([AP]M?)/i;
    $hh = ($hh % 12) + (($ampm =~ m/AM?/i) ? 0 : 12);
    return sprintf("%.2d:%.2d", $hh, $mm);
}

I found this code in the bleow link. Please check: Is my pseudo code for changing time format correct?

Upvotes: 1

Related Questions