我想用Perl替换一个字符串;两者长度相同.我想替换所有出现的字符串(不区分大小写),但是我想要保留这个字母的大小写.所以如果第一封信是大写的,替换后的第一个字母也是大写.
例如,如果我想用“bar”替换“foo”,那么我想要
foo ==> bar Foo ==> Bar FOO ==> BAR
在Perl中有一个简单的方法吗?
这可能是你以后:
原文链接:https://www.f2er.com/regex/357202.htmlHow 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