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.
For example, if I want to replace "foo" with "bar", so I want that
foo ==> bar
Foo ==> Bar
FOO ==> BAR
Is there a simple way to do this in Perl?
Create regular expressions to remove uppercase, lowercase, special, numeric, and non-numeric characters from the string as mentioned below: regexToRemoveUpperCaseCharacters = “[A-Z]” regexToRemoveLowerCaseCharacters = “[a-z]” regexToRemoveSpecialCharacters = “[^A-Za-z0-9]”
The toLowerCase() method converts a string to lower case letters. Note: The toUpperCase() method converts a string to upper case letters.
Is the String replace function case sensitive? Yes, the replace function is case sensitive. That means, the word “this” has a different meaning to “This” or “THIS”. In the following example, a string is created with the different case letters, that is followed by using the Python replace string method.
JavaScript String toLowerCase() The toLowerCase() method converts a string to lowercase letters. The toLowerCase() method does not change the original string.
This might be what you are after:
How do I substitute case insensitively on the LHS while preserving case on the RHS?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With