in reply to \G and regexes

If there is no anchoring, the regex can match anywhere inside the string. So given the string AAAATGA, the match can work as follow:
AAAATGA XXX TGA

where XXX stands for the letters matched by (\w\w\w). The first A in the string is not matched by anything. Using \G prevents that.

Perl 6 - links to (nearly) everything that is Perl 6.

Replies are listed 'Best First'.
Re^2: \G and regexes
by 7stud (Deacon) on Apr 05, 2010 at 20:37 UTC

    Ok. After some tests, I get what you are saying.

    The /g flag does not require that further matching must start past the end of the previous match--it just makes a request for any other unique matches. And the regex /(\w\w\w)*?TGA/ can act like the regex /TGA/ because a regex will happily match nothing for *.

    But then why doesn't the /g flag cause this to match four times:

    use strict; use warnings; use 5.010; my $str = 'aaaBBBcccTGA'; while ($str =~ /(?:\w\w\w)*?(TGA)/g) { say $1; say pos $str; }

    Aren't there four unique matches:

    1)  when (\w\w\w) is matched 0 times.
    2)  when (\w\w\w) is matched 1 time.
    3)  when (\w\w\w) is matched 2 times.
    4)  when (\w\w\w) is matched 3 times.

    That suggests that another match must end past the previous match--but that the next match doesn't have to start past the previous match.

    My tests also show that starting the regex with a \A to anchor it to the beginning of the string will cause the regex to match only once:

    use strict; use warnings; use 5.010; my $str = 'aaaBBBcccTGAddTGA'; while ($str =~ /\A(?:\w\w\w)*?(TGA)/g) { say $1; say pos $str; } --output:-- TGA 12

    But then I would expect this to match twice, and it doesn't:

    use strict; use warnings; use 5.010; my $str = 'aaaBBBcccTGAdddTGA'; while ($str =~ /\A(?:\w\w\w)*?(TGA)/g) { say $1; say pos $str; }

    So I guess I don't have any idea what's going on.

      The /g flag does not require that further matching must start past the end of the previous match--it just makes a request for any other unique matches.

      No. It makes a request for another match to the leftright of the end of the previous match. The first match goes up to position 12:

      aaaBBBcccTGAddTGA XXXXXXXXX TGA ^ match ends here
      So the next match sees only <c>ddTGA</cc> to match against.
      Perl 6 - links to (nearly) everything that is Perl 6.
        Do you mean to the 'right' of the end of the previous match?