develooper Front page | perl.perl5.porters | Postings from December 2012

[perl #116228] Regex * quantifier sometimes behaves as non-greedy

Thread Previous | Thread Next
From:
James E Keenan via RT
Date:
December 29, 2012 13:20
Subject:
[perl #116228] Regex * quantifier sometimes behaves as non-greedy
Message ID:
rt-3.6.HEAD-17500-1356787227-55.116228-15-0@perl.org
On Fri Dec 28 09:49:50 2012, rob.dixon@gmx.com wrote:
> 
> Subject: Regex * quantifier sometimes behaves as non-greedy
> Message-Id: <5.16.2_9428_1356716172@Samurai>
> Reply-To: rob.dixon@gmx.com
> To: perlbug@perl.org
> From: rob.dixon@gmx.com
> 
> 
> This is a bug report for perl from rob.dixon@gmx.com,
> generated with the help of perlbug 1.39 running under perl 5.16.2.
> 
> 
> -----------------------------------------------------------------
> 
> This code
> 
> 
>    for (qw/abb aabb/) {
>      printf "%d: %s\n", length $1, $1 if m/(ab*)/;
>    }
> 
> produces
> 
>    3: abb
>    1: a
> 
> As you can see, in the first iteration the entire string is
> correctly matched, whereas in the second iteration the pattern
> matches just `a` when it should match `abb`.
> 

No, the code written is producing the expected results.  You are not
using the '/g' qualifier on your pattern and you are not attempting to
capture all possible matches.  Compare:

#####
printf("%-8s%8s%10s\n" => qw(source length capture));
for my $str (qw/abb aabb/) {
    my @matches;
    (@matches) = $str =~ m/(ab*)/g;
    for my $el (@matches) {
        printf("%-8s%8s%10s\n" => ($str, length($el), $el));
    }
}
#####

This produces:

#####
source    length   capture
abb            3       abb
aabb           1         a
aabb           3       abb
#####

'a' -- which happens to be the first of two matching substrings
encountered -- matches because 'ab*' means: "an 'a' followed by 0 or
more instances of 'b'."

Thank you very much.
Jim Keenan

---
via perlbug:  queue: perl5 status: new
https://rt.perl.org:443/rt3/Ticket/Display.html?id=116228

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About