如何在 Perl 中找到单个字符串的匹配正则表达式的位置?
How can I find position of matched regex of a single string in Perl?
假设 my $string = "XXXXXTPXXXXTPXXXXTP";
如果我想匹配:$string =~ /TP/;
多次和 return 每次的位置,我该怎么做?
我试过$-[0]
、$-[1]
、$-[2]
,但我只得到了$-[0]
的位置。
编辑:
我也试过全局修饰符//g
,还是不行。
你可以试试:
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
}
$-[1]
是第一次抓取的文字位置。您的模式没有捕获。
通过在标量上下文中调用 //g
,只会找到下一个匹配项,这样您就可以获取该匹配项的位置。只需这样做,直到找到所有匹配项。
while ($string =~ /TP/g) {
say $-[0];
}
当然,您也可以轻松地将它们存储在变量中。
my @positions;
while ($string =~ /TP/g) {
push @positions, $-[0];
}
假设 my $string = "XXXXXTPXXXXTPXXXXTP";
如果我想匹配:$string =~ /TP/;
多次和 return 每次的位置,我该怎么做?
我试过$-[0]
、$-[1]
、$-[2]
,但我只得到了$-[0]
的位置。
编辑:
我也试过全局修饰符//g
,还是不行。
你可以试试:
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
}
$-[1]
是第一次抓取的文字位置。您的模式没有捕获。
通过在标量上下文中调用 //g
,只会找到下一个匹配项,这样您就可以获取该匹配项的位置。只需这样做,直到找到所有匹配项。
while ($string =~ /TP/g) {
say $-[0];
}
当然,您也可以轻松地将它们存储在变量中。
my @positions;
while ($string =~ /TP/g) {
push @positions, $-[0];
}