You've been shown why this is not matching as you want, but please also consider that $1 and $2 are only uninitialized because you haven't previously successfully captured a match in your program. If you had, those variables would still contain the matches they captured earlier.
From perlre:
NOTE: Failed matches in Perl do not reset the match variables, which m +akes it easier to write code that tests for a series of more specific + cases and remembers the best match.
Thus it's important to check whether the match succeeded before using $1:
The above code does not give the expected results:#!/usr/bin/perl use strict; use warnings; my $status = "it's a beautiful day but I am feeling crapy"; # note typ +o $status =~ /(beautiful|average|tough)/; print "Day: $1\n"; $status =~ /(happy|alright|crappy)/; print "Feeling: $1\n"; __END__
Add a test and we avoid the bug:[22:08][nick:~/monks]$ perl 1139246.pl Day: beautiful Feeling: beautiful [22:08][nick:~/monks]$
Output:#!/usr/bin/perl use strict; use warnings; my $status = "it's a beautiful day but I am feeling crapy"; # note typ +o if ( $status =~ /(beautiful|average|tough)/ ) { print "Day: $1\n"; } else { print "No match for day\n"; } if ( $status =~ /(happy|alright|crappy)/ ) { print "Feeling: $1\n"; } else { print "No match for feeling\n"; } __END__
[22:13][nick:~/monks]$ perl 1139246.pl Day: beautiful No match for feeling [22:13][nick:~/monks]$
In reply to Re: regex capture group problem
by 1nickt
in thread regex capture group problem
by midiperl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |