On 2011-05-25 16:39, Irfan Sayed wrote:

i have string like this
"2011/05/25 07:24:58 -0700 PDT"  i need to match "2011/05/25"
i wrote reg ex like this: ^\d\d\d\d//\d\d/\d\d$ but it is not working

code is like this


$lin = "2011/05/25 07:24:58 -0700 PDT";
$lin =~ m/^\d\d\d\d//\d\d/\d\d$/;
print "$lin\n";

1. Do you mean matching, or capturing?

2. When there is a slash inside your data, just use a different separator, like {} (see Jim Gibson's answer).

3. '[0-9]' is a better character class here than \d, because \d matches over 200 code points.

4. Use strict and warnings, (see Rob Dixon's answer).


#!/usr/bin/perl -wl
use strict;

my $line = qq{2011/05/25 07:24:58 -0700 PDT\n};

my ($date, $time, $tz_offset, $tz_abbrev ) =
  $line =~ m{\A
     ( [0-9]{4}/[0-9]{2}/[0-9]{2} )  # date
     \s+
     ( [0-9]{2}:[0-9]{2}:[0-9]{2} )  # time
     \s+
     ( [-+][0-9]{4} )                # tz-offset
     \s+
     ( [A-Z]{3} )
  \Z}x;

print sprintf q{date='%s' time='%s' offs='%s' abbr='%s'},
              $date, $time, $tz_offset, $tz_abbrev;
__END__



Alternative-1:

my ($date, $time, $tz_offset, $tz_abbrev ) = split ' ', $line;

Alternative-2:

my %datim;
@datim{qw/ date time tz_offset tz_abbrev /} = split ' ', $line;

Alternative-3:

my %datim;
@datim{qw/ date time tz_offset tz_abbrev /} = $line =~ /\S+/g;

Alternative-4:

Use a module that knows about dates and times.

--
Ruud

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to