如何替换 Perl 正则表达式中第 n 次出现的匹配项?

发布于 2024-08-27 10:44:46 字数 940 浏览 8 评论 0原文

跟进之前的问题 提取第 n 个正则表达式匹配,我现在需要替换该匹配(如果找到)。

我认为我可以定义提取子例程并在使用 /e 修饰符的替换中调用它。我显然错了(诚然,我有一个 XY 问题)。

use strict;
use warnings;

sub extract_quoted { # à la codaddict

        my ($string, $index) = @_;
        while($string =~ /'(.*?)'/g) {
                $index--;
                return $1 if(! $index);
        }
        return;
}

my $string = "'How can I','use' 'PERL','to process this' 'line'";

extract_quoted ( $string, 3 );
$string =~ s/&extract_quoted($string,2)/'Perl'/e;

print $string; # Prints 'How can I','use' 'PERL','to process this' 'line'

当然,这种技术还存在许多其他问题:

  • 如果不同位置有相同的匹配怎么办?
  • 如果没有找到匹配怎么办?

鉴于这种情况,我想知道可以通过哪些方式来实现。

Following up from an earlier question on extracting the n'th regex match, I now need to substitute the match, if found.

I thought that I could define the extraction subroutine and call it in the substitution with the /e modifier. I was obviously wrong (admittedly, I had an XY problem).

use strict;
use warnings;

sub extract_quoted { # à la codaddict

        my ($string, $index) = @_;
        while($string =~ /'(.*?)'/g) {
                $index--;
                return $1 if(! $index);
        }
        return;
}

my $string = "'How can I','use' 'PERL','to process this' 'line'";

extract_quoted ( $string, 3 );
$string =~ s/&extract_quoted($string,2)/'Perl'/e;

print $string; # Prints 'How can I','use' 'PERL','to process this' 'line'

There are, of course, many other issues with this technique:

  • What if there are identical matches at different positions?
  • What if the match isn't found?

In light of this situation, I'm wondering in what ways this could be implemented.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

秉烛思 2024-09-03 10:44:47

请参阅 perldoc perlvar

use strict; use warnings;

use Test::More tests => 5;

my %src = (
    q{'I want to' 'extract the word' 'PERL','from this string'}
    => q{'I want to' 'extract the word' 'Perl','from this string'},
    q{'What about', 'getting','PERL','from','here','?'}
    => q{'What about', 'getting','Perl','from','here','?'},
    q{'How can I','use' 'PERL','to process this' 'line'}
    => q{'How can I','use' 'Perl','to process this' 'line'},
    q{Invalid} => q{Invalid},
    q{'Another invalid string'} => q{'Another invalid string'}
);

while ( my ($src, $target) = each %src ) {
    ok($target eq subst_n($src, 3, 'Perl'), $src)
}

sub subst_n {
    my ($src, $index, $replacement) = @_;
    return $src unless $index > 0;
    while ( $src =~ /'.*?'/g ) {
        -- $index or return join(q{'},
            substr($src, 0, $-[0]),
            $replacement,
            substr($src, $+[0])
        );
    }
    return $src;
}

输出:

C:\Temp> pw
1..5
ok 1 - 'Another invalid string'
ok 2 - 'How can I','use' 'PERL','to process this' 'line'
ok 3 - Invalid
ok 4 - 'What about', 'getting','PERL','from','here','?'
ok 5 - 'I want to' 'extract the word' 'PERL','from this string'

当然,您需要决定如果传递了无效的 $index 或未找到所需的匹配项。我只是返回上面代码中的原始字符串。

See perldoc perlvar:

use strict; use warnings;

use Test::More tests => 5;

my %src = (
    q{'I want to' 'extract the word' 'PERL','from this string'}
    => q{'I want to' 'extract the word' 'Perl','from this string'},
    q{'What about', 'getting','PERL','from','here','?'}
    => q{'What about', 'getting','Perl','from','here','?'},
    q{'How can I','use' 'PERL','to process this' 'line'}
    => q{'How can I','use' 'Perl','to process this' 'line'},
    q{Invalid} => q{Invalid},
    q{'Another invalid string'} => q{'Another invalid string'}
);

while ( my ($src, $target) = each %src ) {
    ok($target eq subst_n($src, 3, 'Perl'), $src)
}

sub subst_n {
    my ($src, $index, $replacement) = @_;
    return $src unless $index > 0;
    while ( $src =~ /'.*?'/g ) {
        -- $index or return join(q{'},
            substr($src, 0, $-[0]),
            $replacement,
            substr($src, $+[0])
        );
    }
    return $src;
}

Output:

C:\Temp> pw
1..5
ok 1 - 'Another invalid string'
ok 2 - 'How can I','use' 'PERL','to process this' 'line'
ok 3 - Invalid
ok 4 - 'What about', 'getting','PERL','from','here','?'
ok 5 - 'I want to' 'extract the word' 'PERL','from this string'

Of course, you need to decide what happens if an invalid $index is passed or if the required match is not found. I just return the original string in the code above.

北凤男飞 2024-09-03 10:44:47

重新设计 回答之前的问题,匹配n-1次,然后替换下一个。记忆模式使可怜的 Perl 不必一遍又一遍地重新编译相同的模式。

my $_quoted = qr/'[^']+'/; # ' fix Stack Overflow highlighting
my %_cache;
sub replace_nth_quoted { 
  my($string,$index,$replace) = @_;
  my $pat = $_cache{$index} ||=
    qr/ ^
        (                    # $1
          (?:.*?$_quoted.*?) # match quoted substrings...
            {@{[$index-1]}}  # $index-1 times
        )
        $_quoted             # the ${index}th match
      /x;

  $string =~ s/$pat/$1$replace/;
  $string;
}

例如

my $string = "'How can I','use' 'PERL','to process this' 'line'";
print replace_nth_quoted($string, 3, "'Perl'"), "\n";

输出

'How can I','use' 'Perl','to process this' 'line'

Reworking an answer to an earlier question, match n-1 times and then replace the next. Memoizing patterns spares poor Perl having to recompile the same patterns over and over.

my $_quoted = qr/'[^']+'/; # ' fix Stack Overflow highlighting
my %_cache;
sub replace_nth_quoted { 
  my($string,$index,$replace) = @_;
  my $pat = $_cache{$index} ||=
    qr/ ^
        (                    # $1
          (?:.*?$_quoted.*?) # match quoted substrings...
            {@{[$index-1]}}  # $index-1 times
        )
        $_quoted             # the ${index}th match
      /x;

  $string =~ s/$pat/$1$replace/;
  $string;
}

For example

my $string = "'How can I','use' 'PERL','to process this' 'line'";
print replace_nth_quoted($string, 3, "'Perl'"), "\n";

outputs

'How can I','use' 'Perl','to process this' 'line'
随心而道 2024-09-03 10:44:46

编辑: leonbloy 首先提出了这个解决方案。如果您想投票,请先投票 leonbloy。

受到 leonbloy(之前)的回答的启发:

$line = "'How can I','use' 'PERL' 'to process this';'line'";
$n = 3;
$replacement = "Perl";

print "Old line: $line\n";
$z = 0;
$line =~ s/'(.*?)'/++$z==$n ? "'$replacement'" : "'$1'"/ge;
print "New line: $line\n";

Old line: 'How can I','use' 'PERL' 'to process this';'line'
New line: 'How can I','use' 'Perl' 'to process this';'line'

EDIT: leonbloy came up with this solution first. If your tempted to upvote it, upvote leonbloy's first.

Somewhat inspired by leonbloy's (earlier) answer:

$line = "'How can I','use' 'PERL' 'to process this';'line'";
$n = 3;
$replacement = "Perl";

print "Old line: $line\n";
$z = 0;
$line =~ s/'(.*?)'/++$z==$n ? "'$replacement'" : "'$1'"/ge;
print "New line: $line\n";

Old line: 'How can I','use' 'PERL' 'to process this';'line'
New line: 'How can I','use' 'Perl' 'to process this';'line'
最美不过初阳 2024-09-03 10:44:46

或者你可以做一些像

use strict;
use warnings;

my $string = "'How can I','use' .... 'perl','to process this' 'line'";

my $cont =0;
sub replacen { # auxiliar function: replaces string if incremented counter equals $index
        my ($index,$original,$replacement) = @_;
        $cont++;
        return $cont == $index ? $replacement: $original;
}

#replace the $index n'th match (1-based counting) from $string by $rep
sub replace_quoted {
        my ($string, $index,$replacement) = @_;
        $cont = 0; # initialize match counter
        $string =~ s/'(.*?)'/replacen($index,$1,$replacement)/eg;
        return $string;
}

my $result = replace_quoted ( $string, 3 ,"PERL");
print "RESULT: $result\n";

“全局”$cont 变量有点难看的事情,可以改进,但你明白了。

更新:更紧凑的版本:

use strict;
my $string = "'How can I','use' .... 'perl','to process this' 'line'";

#replace the $index n'th match (1-based counting) from $string by $replacement
sub replace_quoted {
        my ($string, $index,$replacement) = @_;
        my $cont = 0; # initialize match counter
        $string =~ s/'(.*?)'/$cont++ == $index ? $replacement : $1/eg;
        return $string;
}

my $result = replace_quoted ( $string, 3 ,"PERL");
print "RESULT: $result\n";

Or you can do something as this

use strict;
use warnings;

my $string = "'How can I','use' .... 'perl','to process this' 'line'";

my $cont =0;
sub replacen { # auxiliar function: replaces string if incremented counter equals $index
        my ($index,$original,$replacement) = @_;
        $cont++;
        return $cont == $index ? $replacement: $original;
}

#replace the $index n'th match (1-based counting) from $string by $rep
sub replace_quoted {
        my ($string, $index,$replacement) = @_;
        $cont = 0; # initialize match counter
        $string =~ s/'(.*?)'/replacen($index,$1,$replacement)/eg;
        return $string;
}

my $result = replace_quoted ( $string, 3 ,"PERL");
print "RESULT: $result\n";

A little ugly the "global" $cont variable, that could be polished, but you get the idea.

Update: a more compact version:

use strict;
my $string = "'How can I','use' .... 'perl','to process this' 'line'";

#replace the $index n'th match (1-based counting) from $string by $replacement
sub replace_quoted {
        my ($string, $index,$replacement) = @_;
        my $cont = 0; # initialize match counter
        $string =~ s/'(.*?)'/$cont++ == $index ? $replacement : $1/eg;
        return $string;
}

my $result = replace_quoted ( $string, 3 ,"PERL");
print "RESULT: $result\n";
故人的歌 2024-09-03 10:44:46

如果正则表达式并不比您所拥有的复杂太多,您可以在 split 之后进行编辑和 join

$line = "'How can I','use' 'PERL','to process this' 'line'";

$n = 3;
$new_text = "'Perl'";
@f = split /('.*?')/, $line;
# odd fields of @f contain regex matches
# even fields contain the text between matches
$f[2*$n-1] = $new_text;
$new_line = join '', @f;

If the regex isn't too much more complicated than what you have, you could follow a split with an edit and a join:

$line = "'How can I','use' 'PERL','to process this' 'line'";

$n = 3;
$new_text = "'Perl'";
@f = split /('.*?')/, $line;
# odd fields of @f contain regex matches
# even fields contain the text between matches
$f[2*$n-1] = $new_text;
$new_line = join '', @f;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文