perl regular expressions return last matched occurence?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Dustin D.

    perl regular expressions return last matched occurence?

    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
  • Rich

    #2
    Re: perl regular expressions return last matched occurence?

    blackened@austi n.rr.com (Dustin D.) wrote in message news:<7259a2ce. 0308261512.2775 d3cf@posting.go ogle.com>...[color=blue]
    > 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[/color]

    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

    Comment

    Working...