perl regular expressions return last matched occurence?

Discussion in 'Perl' started by Dustin D., Aug 27, 2003.

  1. Dustin D.

    Dustin D. Guest

    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
    Dustin D., Aug 27, 2003
    #1
    1. Advertising

  2. Dustin D.

    Rich Guest

    (Dustin D.) wrote in message news:<>...
    > 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
    Rich, Aug 28, 2003
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. natG
    Replies:
    4
    Views:
    9,668
  2. Sean Berry
    Replies:
    10
    Views:
    688
  3. loial
    Replies:
    2
    Views:
    747
    Patricia Shanahan
    Oct 23, 2008
  4. John Griffiths

    find next occurence, regular expressions

    John Griffiths, Dec 30, 2007, in forum: Ruby
    Replies:
    2
    Views:
    115
    Wolfgang Nádasi-Donner
    Dec 30, 2007
  5. Noman Shapiro
    Replies:
    0
    Views:
    232
    Noman Shapiro
    Jul 17, 2013
Loading...

Share This Page