字符串匹配和Text :: Match :: FastAlternatives

时间:2014-07-14 23:07:53

标签: regex performance perl

我需要在Perl中的许多长字符串中找到所有出现的很多短字符串。就像

my $count = () = $bigstr =~ /$smallstr/g

由于正则表达式花了很多时间,我进入了字符串匹配算法并找到了Perl模块Text::Match::FastAlternatives。在文档中,它只说这个模块可以用来查找是否在另一个字符串中找到了一个字符串。但有没有办法用Text::Match::FastAlternatives计算所有出现次数?真希望如此。谢谢你的关注。

1 个答案:

答案 0 :(得分:0)

每次必须重新分析正则表达式时,是的,这需要时间。

我会建议Benchmarking不同的解决方案,但加快速度的一种方法是在匿名子程序中缓存所有要匹配的字符串。

类似下面的伪代码:

use strict;
use warnings;

my @short_strings = (...);

my @long_strings = (...);

my @match_subs = map {
    my $code = "sub { return scalar(() = shift =~ /\Q$_\E/g }";
    my $sub = eval $code;
    die "Unable to cache sub $code: $@" if $@;
    $sub
} @short_strings;

for my $data (@long_strings) {
    my $count;
    $count += $_->($data) for @match_subs;
    print $count;
}
相关问题