我正在寻找将表现如下的正则表达式:
我的主意是
while($string =~ m/(([a-zA-Z])([a-zA-Z]))/g) {
print "$1-$2 ";
}
但这确实有些不同。
最佳答案
这很棘手。您必须捕获它,保存它,然后强制回溯。
您可以通过以下方式做到这一点:
use v5.10; # first release with backtracking control verbs
my $string = "hello, world!";
my @saved;
my $pat = qr{
( \pL {2} )
(?{ push @saved, $^N })
(*FAIL)
}x;
@saved = ();
$string =~ $pat;
my $count = @saved;
printf "Found %d matches: %s.\n", $count, join(", " => @saved);
产生这个:
Found 8 matches: he, el, ll, lo, wo, or, rl, ld.
如果您没有v5.10或感到头疼,可以使用以下命令:
my $string = "hello, world!";
my @pairs = $string =~ m{
# we can only match at positions where the
# following sneak-ahead assertion is true:
(?= # zero-width look ahead
( # begin stealth capture
\pL {2} # save off two letters
) # end stealth capture
)
# succeed after matching nothing, force reset
}xg;
my $count = @pairs;
printf "Found %d matches: %s.\n", $count, join(", " => @pairs);
产生与以前相同的输出。
但是您可能仍然会头疼。
关于regex - Perl Regex多个匹配项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15279235/