Re: need regular expression
by saintmike (Vicar) on Nov 02, 2005 at 07:37 UTC
|
for(qw(4-10-31 14-11-31)) {
/(\d+)(-.*)/ && printf "%d%s\n", 2000+$1, $2;
}
Note that this obviously doesn't work for pre-2000 dates like 94-10-31. | [reply] [d/l] |
Re: need regular expression
by tilly (Archbishop) on Nov 02, 2005 at 08:08 UTC
|
Untested.
s/(\d?\d)(-\d?\d-\d?\d)/(2000+$1).$2/eg | [reply] [d/l] |
|
s/(\d?\d)(-\d?\d)-(\d?\d)/(2000+$1).sprintf("%02g", $2).sprintf("%02g"
+,$3)/eg
could do it, but that's similarly untested :-) | [reply] [d/l] |
|
The listed examples didn't indicate to me that we need to worry about anything other than the first number, and adding 2000 to a 1 digit number definitely results in a 4 digit one. :-)
But if that's your spec, then try s/(\d?\d)-(\d?\d)-(\d?\d)/sprintf("20%02d-%02d-%02d", $1, $2, $3)/eg
| [reply] [d/l] |
Re: need regular expression
by samizdat (Vicar) on Nov 02, 2005 at 13:42 UTC
|
But I need it to be done using single regular expression.
Smells like homework to me... jesuashok, 'fess up? | [reply] |
|
I agree. In the "Real World", you probably would want to use a module like DateTime to do this sort of thing.
| [reply] |
Re: need regular expression
by ioannis (Abbot) on Nov 02, 2005 at 08:23 UTC
|
for ( my @dates = qw( 4-10-31 14-11-31 ) ) {
s/
^
(\d)
(\d)?
(-\d{1,2}-\d{1,2})
$
/($2?"20$1":"200").$1.$+/ex
and print;
}
| [reply] [d/l] |
|
This formula is simpler than the one earlier. The main
insight here is to avoid strings; it is better to use
arithmetic addition to construct the 'year' string (i.e. 20xx) .
for ( my @dates = qw( 4-10-31 14-11-31 ) ) {
s/
^
(\d{1,2})
((?:-\d{1,2}){2})
$
/(2000+$1).$+/xe
and print;
}
| [reply] [d/l] |
|
I prefer to use strings - in that case, it becomes easy to deal with 3 or 4 digit years as well:
my @dates = qw /4-10-31 14-11-31 1979-10-10/;
for (@dates) {
s/(\d+)/substr("2000", 0, -length($1)).$1/e;
print "$_\n";
}
__END__
2004-10-31
2014-11-31
1979-10-10
| [reply] [d/l] |
Re: need regular expression
by davido (Cardinal) on Nov 02, 2005 at 08:46 UTC
|
The following will work correctly if the year is specified as 0, 1, 11, 111, or even 1111 (ones representing any digit):
use strict;
use warnings;
my( @dates ) = ( '4-10-31', '14-11-31' );
foreach my $date ( @dates ) {
my $string = $date;
$string =~ s/^(\d+)/
my $year=2000;
substr($year,4-length($1),length($1))=$1;
$year/e;
print $string, "\n";
}
You can even override '2000' as being the base year by including the entire four-digit year, as in "1987-10-31".
| [reply] [d/l] |
Re: need regular expression
by l.frankline (Hermit) on Nov 02, 2005 at 09:06 UTC
|
Hi,
Try this...
$_='4-10-31';
print $_ if (s/(\d{1,2})(\-\d{1,2}\-\d{1,2})/"2". 0 x (4 - length($1)+1-2).$1.$2/e);
frank.
| [reply] [d/l] [select] |