Perl Regex-获取所有匹配项的偏移量,而不是一个 [英] Perl Regex - Get offset of all the matches instead of one
问题描述
我想在文件中搜索字符串,然后获取所有匹配项的偏移量. 文件内容如下:
I want to search a file for a string and then get offsets for all the matches. The content of file is as below:
sometext
sometext
AAA
sometext
AAA
AAA
sometext
我正在将整个文件读入字符串$text
,然后对AAA
进行正则表达式匹配,如下所示:
I am reading this whole file into a string $text
and then doing a regex match for AAA
as follows:
if($text =~ m/AAA/g) {
$offset = $-[0];
}
这将仅提供一个AAA
的偏移量.如何获得所有匹配项的抵消额?
This will give offset of only one AAA
. How can I get offset of all the matches?
我知道我们可以使用如下语法获取数组中的所有匹配项:
I know that we can get all matches in an array using syntax like this:
my @matches = ($text =~ m/AAA/g);
但是我想要偏移量不匹配的字符串.
But I want offset not matched string.
当前,我正在使用以下代码获取所有匹配项的偏移量:
Currently I am using following code to get offsets of all matches:
my $text= "sometextAAAsometextAAA";
my $regex = 'AAA';
my @matches = ();
while ($text =~ /($regex)/gi){
my $match = $1;
my $length = length($&);
my $pos = length($`);
my $start = $pos + 1;
my $end = $pos + $length;
my $hitpos = "$start-$end";
push @matches, "$match found at $hitpos ";
}
print "$_\n" foreach @matches;
但是有没有更简单的方法呢?
But is there a simpler way to to this?
推荐答案
我认为Perl中没有内置的方法可以做到这一点.但是从如何获得我在Perl中找到了正则表达式匹配项的位置吗?:
I don't think there's a built-in way to do this in Perl. But from How can I find the location of a regex match in Perl?:
sub match_all_positions {
my ($regex, $string) = @_;
my @ret;
while ($string =~ /$regex/g) {
push @ret, [ $-[0], $+[0] ];
}
return @ret
}
这篇关于Perl Regex-获取所有匹配项的偏移量,而不是一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!