我可以从 this 看到回答,如果我这样做
sub match_all_positions {
my ($regex, $string) = @_;
my @ret;
while ($string =~ /$regex/g) { push @ret, $-[0] }
return @ret
}
print join ',', match_all_positions('0{3}', '001100010000');
我得到
4,8
我需要怎么做才能获得所有匹配项的索引,即使重叠,例如上面示例中的位置 8 和 9?
我可以
sub match_all_positions_b {
my ($substr, $string) = @_;
return unless index($string, $substr) > 0;
my @res;
my $i = 0;
while ($i <= (length($string) - $length)) {
$i = index($string, $substr, $i);
last if $i < 0;
push @res, $i++;
}
return @res;
}
print join ',', match_all_positions_b('000', '001100010000');
这只是让我匹配一个子字符串,或者
sub match_all_positions_c {
my ($substr, $string) = @_;
my $re = '^' . $substr;
my @res;
for (0..(length($string) - $length)) {
push @res, $_ if substr($string, $_) =~ /$re/;
}
return @res;
}
print join ',', match_all_positions_c('0{3}', '001100010000');
这是慢两倍。
有没有办法获得所有匹配项,即使它们重叠?或者我应该只考虑速度损失,因为它是使用正则表达式匹配所固有的?
最佳答案
您需要为 zero-width look-ahead 更新正则表达式匹配。
尝试像这样调用你的函数:
print join ',', match_all_positions('(?=0{3})', '001100010000');
关于regex - 如何在 Perl 中找到正则表达式匹配的 _all_ 位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45731046/