Perl正则表达式:计算领先的子串

时间:2015-03-17 19:57:14

标签: regex perl

是否有可以计算子字符串出现在另一个字符串开头的频率的Perl正则表达式?

例如

my $string = "../../../../../../../../../Downloads/../Testing/../";

my $countstr = "../";

结果应该是9,因为在../的开头有9次出现$string

1 个答案:

答案 0 :(得分:4)

您可以使用全局正则表达式和\G锚点执行此操作,如此

use strict;
use warnings;

my $string   = '../../../../../../../../../Downloads/../Testing/../';
my $countstr = '../';

my $n = () = $string =~ /\G\Q$countstr/g;

print $n, "\n";

<强>输出

9