in reply to Re^2: Match, Capture and get position of multiple patterns in the same string
in thread Match, Capture and get position of multiple patterns in the same string

The regex match inside the while condition stores its current position in pos($string) (see pos for detail), which the substitution resets, so on the next iteration it starts from the beginning again.

So if you insist on doing the matching and substitution in two different steps, you have to manually set pos($string) after the substitution:

use strict; use warnings; use 5.010; my $string = "CATINTHEHATWITHABAT"; my $regex = qr{\wAT}i; while ($string =~ m/($regex)/g){ my $match = $1; my $start = $-[0]; my $end = $+[0]; my $hitpos = "$start-$end"; my $lcmatch = lc($match); $string =~ s/$match/$lcmatch/g; # in the next iteration start over where we left off pos($string) = $end; say "$match found at $hitpos "; } say "string: $string";

Since you put parenthesis around the regex, ${^MATCH} can be replaced by the shorter $1, and there's no need for the /p modifier.

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

Replies are listed 'Best First'.
Re^4: Match, Capture and get position of multiple patterns in the same string
by richardwfrancis (Beadle) on Nov 13, 2009 at 08:33 UTC

    Thanks moritz that makes perfect sense. I didn't realise the substitution would reset this. I've implemented that now, thank you.

    Do I need to distribute points or anything in this forum?

    Cheers,

    Rich
      Do I need to distribute points or anything in this forum?

      You don't need to do anything, but it's considered good style to upvote helpful replies and good question, once you've got some votes.

      See also Voting/Experience System and The Role of XP in PerlMonks.

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