gpt4 book ai didi

regex - Perl 正则表达式多重匹配

转载 作者:行者123 更新时间:2023-12-04 16:35:05 25 4
gpt4 key购买 nike

我正在寻找一个行为如下的正则表达式:

input: "hello world."

output: he, el, ll, lo, wo, or, rl, ld



我的想法是
    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 正则表达式多重匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15279235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com