How can I find position of matched regex of a single string in Perl?

348 Views Asked by At

Let's say my $string = "XXXXXTPXXXXTPXXXXTP"; If I want to match: $string =~ /TP/; multiple times and return the position for each, how would I do so?

I have tried$-[0], $-[1], $-[2] but I only get a position for $-[0].

EDIT: I have also tried the global modifier //g and it still does not work.

2

There are 2 best solutions below

1
On BEST ANSWER

$-[1] is the position of the text captured by the first capture. Your pattern has no captures.

By calling //g in scalar context, only the next match is found, allowing you to grab the position of that match. Simply do this until you've found all the matches.

while ($string =~ /TP/g) {
   say $-[0];
}

Of course, you could just as easily store them in a variable.

my @positions;
while ($string =~ /TP/g) {
   push @positions, $-[0];
}
4
On

You could try:

use feature qw(say);
use strict;
use warnings;

my $str = "XXXXXTPXXXXTPXXXXTP";

# Set position to 0 in order for \G anchor to work correctly
pos ($str) = 0;

while ( $str =~ /\G.*?TP/s) {
    say ($+[0] - 2);
    pos ($str) = $+[0]; # update position to end of last match
}