Re: did I get greedy quantifiers wrong ?
- From: chas.owens@xxxxxxxxx (Chas Owens)
- Date: Thu, 31 May 2007 09:45:24 -0400
On 5/31/07, Sharan Basappa <sharan.basappa@xxxxxxxxx> wrote:
Thanks Chas ..
I was wondering about the first regex str =~ m/m(.*i)(.*pi)/;
did not match all the way till mississip. In fact my initial understanding
was that the regex would match mississippi leaving nothing for second
regex. Can you throw some light on this ..
On 5/31/07, Chas Owens <chas.owens@xxxxxxxxx> wrote:
> On 5/31/07, Sharan Basappa <sharan.basappa@xxxxxxxxx> wrote:
> snip
> > $str =~ m/m(.*i?)(.*pi)/;
> snip
>
> ? only means non-greedy when following a * or a +. When it follows a
> pattern it means optional.
Nope, because then the match will fail. Greediness will not cause the
match to fail; it only affects how much of the string is matched.
#!/usr/bin/perl
use strict;
use warnings;
$_ = "abababab";
print "trying /(a.*b)/g\n";
my $i = 1;
while (/(a.*b)/g) {
print "\t$i: $1\n";
$i++;
}
print "trying /(a.*?b)/g\n";
$i = 1;
while (/(a.*?b)/g) {
print "\t$i: $1\n";
$i++;
}
print "trying /(a.+b)/g\n";
my $i = 1;
while (/(a.+b)/g) {
print "\t$i: $1\n";
$i++;
}
print "trying /(a.+?b)/g\n";
$i = 1;
while (/(a.+?b)/g) {
print "\t$i: $1\n";
$i++;
}
prints
trying /(a.*b)/g
1: abababab
trying /(a.*?b)/g
1: ab
2: ab
3: ab
4: ab
trying /(a.+b)/g
1: abababab
trying /(a.+?b)/g
1: abab
2: abab
.
- References:
- did I get greedy quantifiers wrong ?
- From: Sharan Basappa
- Re: did I get greedy quantifiers wrong ?
- From: Chas Owens
- Re: did I get greedy quantifiers wrong ?
- From: Sharan Basappa
- did I get greedy quantifiers wrong ?
- Prev by Date: Re: Passing arguments to subroutine
- Next by Date: Re: Passing arguments to subroutine
- Previous by thread: Re: did I get greedy quantifiers wrong ?
- Next by thread: Re: did I get greedy quantifiers wrong ?
- Index(es):