我想在 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/3116434/