in reply to greedy search
$str = 'aaaaa'; $str =~ s/a+/b/;
Since '+' is greedy, you end up with 'b' in $str.
If '+' wasn't greedy, you'd end up with 'baaaa' in $str.
You can make '+' non-greedy by following it with a '?':
$str1 = $str2 = '111b222c333c444'; $str1 =~ s/b.+c//; # $str1 contains '111444'. $str2 =~ s/b.+?c//; # $str2 contains ''111333c444'.
'*' and '?' can similarly be modified with a '?'.
Both greedy and non-greedy are useful. Use whichever one you need in a particular situation.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: greedy search
by monarch (Priest) on Jun 03, 2005 at 05:45 UTC |