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

标签 regex perl backreference

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

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/

相关文章:

python - 用大括号包裹数字的正则表达式?

python - 使用正则表达式搜索和过滤 pandas 数据框

regex - 用于句子中介词的 Python 正则表达式

linux - 使用 getgrnam() 只查询本地组

linux - Perl 进程解析

Perl - 散列和列的散列 :(

javascript - 一个简单的 javascript 正则表达式反向引用

java - 匹配器: "No match found..."

java - 使用动态匹配器进行模式匹配

regex - 如何否定反向引用正则表达式