如何替换字符串并保留其大写/小写 [英] How to replace string and preserve its uppercase/lowercase

查看:91
本文介绍了如何替换字符串并保留其大写/小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to replace one string with the other in Perl; both are of the same length. I want to replace all occurrences of the string (case insensitive), but I want that the case of the letter will be preserved. So if the first letter was upper case, the first letter after the replacement will be upper case also.

例如,如果我想将"foo"替换为"bar",那么我想要

For example, if I want to replace "foo" with "bar", so I want that

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

在Perl中有一种简单的方法吗?

Is there a simple way to do this in Perl?

推荐答案

这可能是您想要的:

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

This is copied almost directly from the above link:

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

这篇关于如何替换字符串并保留其大写/小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆