perl regular expressions return last matched occurence?

D

Dustin D.

If I attempt to crop a string using regular expressions and the ()
operator for grouping, Perl always seems to return the last match.
For instance, if I have the following:

my $test = "a0\nb0\nc0\na1\nb1\nc1\n";
$test =~ s/.*(\w\d\n).*/$1/s;
print "$test";

The output would be:

c1

I don't understand why it's not a0? Any ideas?

Thanks,
Dustin
 
R

Rich

If I attempt to crop a string using regular expressions and the ()
operator for grouping, Perl always seems to return the last match.
For instance, if I have the following:

my $test = "a0\nb0\nc0\na1\nb1\nc1\n";
$test =~ s/.*(\w\d\n).*/$1/s;
print "$test";

The output would be:

c1

I don't understand why it's not a0? Any ideas?

Thanks,
Dustin

It's all about greed.

Your .* is being greedy and going to the last group of word characters
which is c1. To stop it from being greedy add a ? after the first .*
and it should work the way you expect

Rich
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top