CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Regular Expressions: Re: [alferic] split string into dates: Edit Log



BillKSmith
Veteran

Apr 7, 2014, 10:09 AM


Views: 23972
Re: [alferic] split string into dates

The following code should match all valid dates (Ambiguities resolved arbitrarily by greediness). It correctly fails to match most invalid dates (It assumes that all months have 31 days. Therefore it will incorrectly match patterns such as Feb 31.)


Code
use strict; 
use warnings;
use Time::timegm qw(timegm);
my @given = (
'3122014_50437_AM', ##read as Mar 12, 2014 5:04:37 AM
'112014_112532_PM', ##read as Jan 1,2014 11:25:32 PM
'12152013_63524_PM', ##read as Dec 15, 2014 6:35:24 PM
);
my @Month = qw(xxx Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
my $YR = qr/19[7-9][0-9]|20[0-9][0-9]/;
my $MO = qr/[1-9]|1[0-2]/;
my $DY = qr/[1-9]|[12][0-9]|3[01]/;
my $HR = qr/0?[1-9]|1[0-2]/;
my $MN = qr/0?[1-9]|[1-5][0-9]/;
my $SC = qr/0?[1-9]|[1-5][0-9]/;
my $AP = qr/[AP]M/i;


foreach (@given) {
if (/($MO)($DY)($YR)_($HR)($MN)($SC)_($AP)/) {
my @date = ($Month[$1], $2, $3, $4, $5, $6, $7);
printf "%3s %2d, %4d %2d:%2d:%2d %3s\n", @date;
my $yy = $1 - 1900;
my $mm = $2 -1;
my $dd = $3;
my $hr = $4 + ($7 =~ /^pm$/i) ? 12 : 0;
my $min= $5;
my $ss = $6;
my $datetime = timegm($ss, $min, $hr, $dd, $mm, $yy);
print "$datetime\n";
}
else{
warn "No date found in '$_'\n";
}
}


Update: Fixed code error unrelated to regex.
Good Luck,
Bill

(This post was edited by BillKSmith on Apr 8, 2014, 4:25 AM)


Edit Log:
Post edited by BillKSmith (Veteran) on Apr 8, 2014, 4:25 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives