gpt4 book ai didi

python - 我如何在表达式中使用 Perl 的 s///?

转载 作者:太空狗 更新时间:2023-10-29 21:13:40 25 4
gpt4 key购买 nike

找这个我很头疼:如何在表达式中使用 s///而不是赋值。为了阐明我的意思,我正在寻找在以下上下文中使用时与 python 的 re.sub(...) 等效的 perl:

newstring = re.sub('ab', 'cd', oldstring)

到目前为止,我知道如何在 perl 中执行此操作的唯一方法是:

$oldstring =~ s/ab/cd/;
$newstring = $oldstring;

注意额外的分配。

最佳答案

您可以使用 ($new = $old) =~ s/whatever/whateverelse/; 来实现您正在寻找的完全相同的功能:

use strict;
my $old = "OLD";
my $new;
($new = $old) =~ s/OLD/NEW/;
print "old=$old, new=$new";

产生:

old=OLD, new=NEW

正是你想要的

如果你正在寻找一个函数,你可以定义你自己的函数来避免赋值:

use strict;
sub re_sub {
my ($find, $replace, $old) = @_;
my $new = $old;
$new =~ s/$find/$replace/;
return $new;
}

my $old = "ab";
my $new = re_sub('ab', 'cd', $old);
print "new=$new\n";

new=cd 的结果。

关于python - 我如何在表达式中使用 Perl 的 s///?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2664812/

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