Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl regex and capturing groups

Tags:

regex

perl

The following prints ac | a | bbb | c

    #!/usr/bin/env perl
    use strict;
    use warnings;
    # use re 'debug';
    
    my $str = 'aacbbbcac';
    
    if ($str =~ m/((a+)?(b+)?(c))*/) {
       print "$1 | $2 | $3 | $4\n";
    }

It seems like failed matches do not reset the captured group variables. What am I missing?

like image 231
snoofkin Avatar asked Oct 28 '13 18:10

snoofkin


1 Answers

As odd as it seems this is the "expected" behavior. Here's a quote from the perlre docs:

NOTE: Failed matches in Perl do not reset the match variables, which makes it easier to write code that tests for a series of more specific cases and remembers the best match.

like image 67
Paul Rubel Avatar answered Sep 19 '22 00:09

Paul Rubel