gpt4 book ai didi

regex - 如何匹配两个实例并在 perl 中使用正则表达式替换第一个实例?

转载 作者:行者123 更新时间:2023-12-01 11:03:29 25 4
gpt4 key购买 nike

如果返回两个匹配项,我只想替换第一个实例。

例子:

$sen = "The quick brown fox jump over the lazy dog, fox is quick";

我怎样才能只匹配第一个 fox 并将其替换为 wolf,反之亦然。

输出:

The quick brown wolf jump over the lazy dog, fox is quick 

或:

The quick brown fox jump over the lazy dog, wolf is quick 

谢谢。

最佳答案

使用全局选项 /g 计算匹配项,将匹配项列表分配给空列表以获得计数(比临时变量更好)。首先替换是基本的。第二个使用一个计数器,该计数器在每次匹配时递增,并在适当的时间替换。

注意使用字边框\b防止误匹配,如firefoxfoxy lady

代码:

use strict;
use warnings;
use v5.10; # only required for say, use print instead if your version is lower

my $fox = 'fox';
my $wolf = 'wolf';
my $sen = "The quick brown fox jump over the lazy dog, fox is quick";

if ((()=$sen =~ /\b$fox\b/g) == 2) { # counting matches
my $first = $sen;
$first =~ s/\b$fox\b/$wolf/; # replacing first
my $second = $sen;
my $i = 0;
$second =~ s/\b$fox\b/ ++$i == 2 ? $wolf : $fox/eg; # replacing second
say for $first, $second;
}

输出:

The quick brown wolf jump over the lazy dog, fox is quick
The quick brown fox jump over the lazy dog, wolf is quick

如果你想要一个更可重用的代码,你可以用它做一个子程序。

my $second = replace_nr($sen, $fox, $wolf, 2);
...
sub replace_nr {
my ($str, $find, $replace, $num) = @_;
my $i = 0;
$str =~ s/\b($find)\b/ ++$i == $num ? $replace : $find/eg;
return $str;
}

然后您甚至可以将 sub 用于两个替换:

my $first  = replace_nr($sen, $fox, $wolf, 1);
my $second = replace_nr($sen, $fox, $wolf, 2);

关于regex - 如何匹配两个实例并在 perl 中使用正则表达式替换第一个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8485895/

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