Welcome to WebmasterWorld Guest from 54.167.82.170

Forum Moderators: coopster & jatar k & phranque

Message Too Old, No Replies

Formatting U.S dates

     

Davo1977

12:31 pm on Aug 5, 2008 (gmt 0)

5+ Year Member



This is an exercise i have discovered in a book and would like to find an answer for a better understanding of Perl Regular Expressions.

The question simply wants me to demonstrate changing different date formats into one one format. To change 3/1/2004 or 3.1.2004 into 3-1-2004.

I believe the date 3-1-2003 matches the following code -

$date =~ /^(0[1-9]1[012])[- /.](0[1-9][12][0-9]3[01])[- /.](1920)\d\d

But i need to use the substitution operator to replace the following dates from 3/1/2004 to 3-1-2004.

Anyone with some suggestions please?

regards
Dave

perl_diver

4:30 pm on Aug 5, 2008 (gmt 0)

5+ Year Member



it depends on if the string is only the date or if there is more text in the string.

if there is more text in the string:



$date =~ s/(\d+)[/.](\d+)[/.](\d+)/$1-$2-$3/g;

only the date:



$date =~ tr#/.#-#;

rocknbil

5:51 pm on Aug 5, 2008 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Except you need to escape the slashes or it gives you an unmatched [ error:

$date =~ s/(\d+)[\/.](\d+)[\/.](\d+)/$1-$2-$3/g;

A dissection of perl diver's code, I've added an x modifier to allow the comments and white space.


#!/usr/bin/perl
$date = '08/05/2008';
print "before $date\n";
#$date =~ s/(\d+)[\/.](\d+)[\/.](\d+)/$1-$2-$3/g;
$date =~ s/ # substitute this match . . .
(\d+) # one or more (+) of any digit. Store this value in $1
[\/.] # followed by ONE slash or dot
(\d+) # followed by one or more digits, store in $2
[\/.] # followed by another slash or dot
(\d+) # followed by one or more digits, store in $3
/$1-$2-$3/gx; # replace with this. Note you can also do $3-$1-$2
# Apply globally (g), allow white space and comments(x)
print "after $date\n";

perl_diver

6:51 pm on Aug 5, 2008 (gmt 0)

5+ Year Member



Except you need to escape the slashes or it gives you an unmatched [ error

oops.... thanks.

 

Featured Threads

Hot Threads This Week

Hot Threads This Month