这是一种方法。这需要使用(?(condition)true-sub-expression|false-sub-expression) 构造内的(?{code}) 块在RE 内更新外部计数器。请参阅perldoc perlre 了解说明。
use Modern::Perl;
use re qw/eval/; # Considered experimental.
my $string = 'Hello world!';
my $count = 2;
my $re = qr/
(l)
(?(?{$count--})|(*FAIL))
/x;
say "Looking for $count instances of 'l' in $string.";
my ( @found ) = $string =~ m/$re/g;
say "Found ", scalar @found, " instances of 'l': @found";
输出是:
Looking for 2 instances of 'l' in Hello world!
Found 2 instances of 'l': l l
这是对相同正则表达式的另一个测试,但这次我们跟踪匹配项的位置只是为了证明它与前两次匹配。
use Modern::Perl;
use strict;
use warnings;
use re qw/eval/; # Considered experimental.
my $string = 'Hello world!';
my $count = 2;
my $position = 0;
my $re = qr/
(l)(?{$position=pos})
(?(?{$count--})|(*FAIL))
/x;
while( $string =~ m/$re/g ) {
say "Found $1 at ", $position;
}
而这次的输出是:
Found l at 3
Found l at 4
我不认为我会推荐这些。如果我正在考虑将匹配限制在字符串的一部分,我会匹配字符串的substr()。但是,如果您喜欢生活在边缘,请继续享受这个 sn-p 的乐趣。
这里是替换:
use Modern::Perl;
use strict;
use warnings;
use re qw/eval/; # Considered experimental.
my $string = 'Hello world!';
say "Before substitution $string";
my $count = 2;
my $re = qr/
(l)
(?(?{$count--})|(*FAIL))
/x;
$string =~ s/$re/L/g;
say "After substitution $string";
还有输出:
Before substitution Hello world!
After substitution HeLLo world!