gpt4 book ai didi

regex - 如何替换字符串并保留其大写/小写

转载 作者:行者123 更新时间:2023-12-03 20:59:39 27 4
gpt4 key购买 nike

我想在 Perl 中用另一个替换一个字符串;两者长度相同。我想替换所有出现的字符串(不区分大小写),但我希望保留字母的大小写。所以如果第一个字母是大写的,替换后的第一个字母也将是大写的。

例如,如果我想用“bar”替换“foo”,那么我想要

foo ==> bar
Foo ==> Bar
FOO ==> BAR

在 Perl 中是否有一种简单的方法可以做到这一点?

最佳答案

这可能是您所追求的:

How do I substitute case insensitively on the LHS while preserving case on the RHS?

这几乎是直接从上面的链接复制的:

sub preserve_case($$) {
my ($old, $new) = @_;
my $mask = uc $old ^ $old;
uc $new | $mask .
substr($mask, -1) x (length($new) - length($old))
}

my $string;

$string = "this is a Foo case";
$string =~ s/(Foo)/preserve_case($1, "bar")/egi;
print "$string\n";

# this is a Bar case

$string = "this is a foo case";
$string =~ s/(Foo)/preserve_case($1, "bar")/egi;
print "$string\n";

# this is a bar case

$string = "this is a FOO case";
$string =~ s/(Foo)/preserve_case($1, "bar")/egi;
print "$string\n";

# this is a BAR case

关于regex - 如何替换字符串并保留其大写/小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21993606/

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