A "greedy" match will indeed get greedy, but it will always allow the last part of the pattern to match if that is possible. Adding a .* at the beginning of the pattern allows that .* to "gobble up" the first START while allowing for the last START to match up with some characters followed by END.
#!/usr/bin/perl -w use strict; my $text ="some text START text I don't want START only text I want EN +D"; my $wanted = ($text =~ /.*START (.*) END$/)[0]; my $wanted2 = ($text =~ /.*(START .* END)$/)[0]; print "wanted=\"$wanted\"\n"; print "wanted2=\"$wanted2\"\n"; __END__ prints: wanted="only text I want" wanted2="START only text I want END"
Update: this: my $wanted  = ($text =~ /.*START (.*) END$/)[0]; may look a bit strange, but this is how to assign $1 to $wanted without having to use $1 as an intermediate variable. The text match is in a list context and I just slice to get the contents of the first matching paren. $2 can be done in the same way...
my ($x,$y) = ($text =~ /.*(START (.*) END)$/)[0,1]; print "x=$x y=$y\n"; #prints: x=START only text I want END y=only text I want
I like this syntax as it "gets to the point" without $1,$2,$3, etc.

In reply to Re: really non greedy match by Marshall
in thread really non greedy match by Allasso

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.