Zerobu
Zerobu

Reputation: 2701

Insertion with Regex to format a date (Perl)

Suppose I have a string 04032010. I want it to be 04/03/2010. How would I insert the slashes with a regex?

Upvotes: 3

Views: 561

Answers (3)

Danny
Danny

Reputation: 14154

To do this with a regex, try the following:

my $var = "04032010";
$var =~ s{ (\d{2}) (\d{2}) (\d{4}) }{$1/$2/$3}x;
print $var;

The \d means match single digit. And {n} means the preceding matched character n times. Combined you get \d{2} to match two digits or \d{4} to match four digits. By surrounding each set in parenthesis the match will be stored in a variable, $1, $2, $3 ... etc.

Some of the prior answers used a . to match, this is not a good thing because it'll match any character. The one we've built here is much more strict in what it'll accept.

You'll notice I used extra spacing in the regex, I used the x modifier to tell the engine to ignore whitespace in my regex. It can be quite helpful to make the regex a bit more readable.

Compare s{(\d{2})(\d{2})(\d{4})}{$1/$2/$3}x; vs s{ (\d{2}) (\d{2}) (\d{4}) }{$1/$2/$3}x;

Upvotes: 4

WhirlWind
WhirlWind

Reputation: 14112

Well, a regular expression just matches, but you can try something like this: s/(..)(..)(..)/$1/$2/$3/

#!/usr/bin/perl

$var = "04032010";
$var =~ s/(..)(..)(....)/$1\/$2\/$3/;
print $var, "\n";

Works for me:

$ perl perltest
04/03/2010

Upvotes: 3

justintime
justintime

Reputation: 3631

I always prefer to use a different delimiter if / is involved so I would go for

s| (\d\d) (\d\d) |$1/$2/|x ;

Upvotes: 2

Related Questions