Welcome to WebmasterWorld Guest from 54.226.47.198

Forum Moderators: coopster & jatar k & phranque

Message Too Old, No Replies

Formatting U.S dates

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

New User

5+ Year Member

joined:June 25, 2008
posts: 24
votes: 0


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

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

Preferred Member

10+ Year Member

joined:Jan 5, 2006
posts:536
votes: 0


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#/.#-#;

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

Senior Member

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

joined:Nov 28, 2004
posts:7999
votes: 0


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";
6:51 pm on Aug 5, 2008 (gmt 0)

Preferred Member

10+ Year Member

joined:Jan 5, 2006
posts:536
votes: 0


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

oops.... thanks.

 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members