Reputation: 1965
I've currenly trying to pull out dates from a file and feed them directly into an array. My regex is working, but I have 6 groups in it, all of which are being added to the array, when I only want the first one.
@dates = (@dates, ($line =~ /((0[1-9]|[12][0-9]|3[01])(\/|\-)(0[1-9]|1[0-2])(\/|\-)([0-9][0-9][0-9][0-9]|[0-9][0-9]))/g ));
is there a simple way to grab the $1 group of a perl regex?
my output is looking like this:
13/04/2009, 13, /, 04, /, 2009, 14-12-09, 14, -, 12, -, 09
Upvotes: 1
Views: 337
Reputation: 3631
That regex looks like the sort of thing that would confuse me when I next pick up the code. I would break it out :
my $date= qr/
(?:0[1-9]|[12][0-9]|3[01]) # day
(?:\/|\-)
(?:0[1-9]|1[0-2]) # month
(?:\/|\-)
(?:[0-9][0-9][0-9][0-9]|[0-9][0-9]) #year
/x ;
You can add the element onto the array using
push @dates, ($line =~ /($date)/ ) ;
You an simplify the seperator bit (notice I have changed to using ( )
rather than / /
to avoid having to backslahs the /
my $date= qr (
(?: 0[1-9] | [12][0-9] | 3[01] # day
[/-]
(?:0[1-9]|1[0-2]) # month
[/-]
(?:\d{4}|\d{2}) #year
)x ;
Upvotes: 4
Reputation: 1965
just found it. You can create a passive group by using ?:
at the start of the group.
@dates = (@dates, ($line =~ /((?:0[1-9]|[12][0-9]|3[01])(?:\/|\-)(?:0[1-9]|1[0-2])(?:\/|\-)(?:[0-9][0-9][0-9][0-9]|[0-9][0-9]))/g ));
by making all other groups passive, now only the first group is added to the array.
Upvotes: 1