MD has asked for the wisdom of the Perl Monks concerning the following question:

Hi

How would I parse the following date/time string...

"2003 % 05 % 1720:55:23"

into the string...

"2003-05-17"

I've tried using split but end up with "2003 05 1720" with the spaces remaing.

Is it possible to translate the original string using a regex?

Regards
MD

Replies are listed 'Best First'.
Re: Regex to parse a date
by broquaint (Abbot) on May 19, 2003 at 09:59 UTC
    my $dt = "2003 % 05 % 1720:55:23"; my $date = sprintf "%d-%02d-%02d", $dt =~ /(\d+) % (\d+) % (\d{2})/; print "date - $date\n"; __output__ date - 2003-05-17
    That seems to do the trick, but you might also want to check out some of the Date and Time modules for more advanced datetime munging.
    HTH

    _________
    broquaint

      Great...thanks Broquaint! I only posted the question 15mins ago and 3 solutions already!!

      I'll check out Date::Manip...thanks..MD:-)

Re: Regex to parse a date
by BrowserUk (Patriarch) on May 19, 2003 at 10:37 UTC

    Following the pronciple of KISS

    my $s = '2003 % 05 % 1720:55:23'; $s =~ s[(....) % (..) % (..).*][$1-$2-$3]; print $s; 2003-05-17

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
      thanks BrowserUk :-))

      MD

Re: Regex to parse a date
by Skeeve (Parson) on May 19, 2003 at 09:56 UTC
    What do you want to do if the pattern doesn't match?
    If you don't care and just want to extract anything almost looking like a date:
    $_="2003 % 05 % 1720:55:23"; s/\D+//g; ($y, $m, $d, $H, $M, $S)=unpack("a4a2a2a2a2a2", $_);
    If you want to take care:
    $_="2003 % 05 % 1720:55:23"; warn "wrong Date" unless ($y, $m, $d, $H, $M, $S)=~ /(\d{4})\s+%\s+([01]\d)\s+%\s+([0-3] +\d)([0-2]\d):([0-5]\d):([0-5]\d)/;
      Thanks Skeeve :-) I'm taking the pattern from a CGI script that puts the date into the % delimeted format.

      Cheers MD

      Long Live Perl Monks!

Re: Regex to parse a date
by TVSET (Chaplain) on May 19, 2003 at 09:57 UTC
    Of course, TIMTOWTD, but:

    #!/usr/bin/perl $a = '2003 % 05 % 1720:55:23'; $a=~ s/[0-9]{2}\:[0-9]{2}\:[0-9]{2}$//; $a=~ s/\s+\%\s+/-/g; print $a,"\n";

    Output:

    2003-05-17

    Leonid Mamtchenkov aka TVSET

      Many thanks Leonid! TIMTOWTD indeed! :-))
Re: Regex to parse a date
by arthas (Hermit) on May 19, 2003 at 10:40 UTC
    My own is this:
    
    my $dt   = "2003 % 05 % 1720:55:23";
    $dt =~ /^(\d{4}) % (\d{2}) % (\d{2})/;
    $date = "$1-$2-$3";
    print "$date\n";
    
    You'll need to change this one if the day of month can have one digit instead of two (i.e. 7 instead of 07). Michele.
      Thanks Michele :-)

      MD