in reply to really non greedy match

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.

Replies are listed 'Best First'.
Re^2: really non greedy match
by ikegami (Patriarch) on May 01, 2010 at 01:30 UTC
    my $wanted = ($text =~ /.*START (.*) END$/)[0]; my $wanted2 = ($text =~ /.*(START .* END)$/)[0]; my ($x,$y) = ($text =~ /.*(START (.*) END)$/)[0,1];
    can be written as
    my ($wanted) = $text =~ /.*START (.*) END$/; my ($wanted2) = $text =~ /.*(START .* END)$/; my ($x,$y) = $text =~ /.*(START (.*) END)$/;
Re^2: really non greedy match
by Allasso (Monk) on May 01, 2010 at 00:45 UTC
    thank you Marshall. I didn't see your post until just now.