Perl regex replace in the same case

If you have a simple regex, replace in perl like this:

($line =~ s/JAM/AAA/g){ 

how can I change it so that it looks at the match and makes the replacement with the same case as the match, for example:

"JAM" will become "AAA" and "jam" will become "aaa"

+7
source share
4 answers
 $line =~ s/JAM/{$& eq 'jam' ? 'aaa' : 'AAA'}/gie; 
+1
source

Unicode based solution:

 use Unicode::UCD qw(charinfo); my %category_mapping = ( Lu # upper-case Letter => 'A', Ll # lower-case Letter => 'a', ); join q(), map { $category_mapping{charinfo(ord $_)->{category}} } split //, 'jam'; # returns aaa join q(), map { $category_mapping{charinfo(ord $_)->{category}} } split //, 'JAM'; # returns AAA 

Here the raw characters are respectively. their categories are a little easier to see than in the other answers.

+4
source

In Perl 5, you can do something like:

 $line =~ s/JAM/$_=$&; tr!AZ!A!; tr!az!a!; $_/gie; 

It handles all the various JAM cases, such as Jam, and it is easy to add other words, for example:

 $line =~ s/JAM|SPAM/$_=$&; tr!AZ!A!; tr!az!a!; $_/gie; 
+3
source

Is something like this possible?

http://perldoc.perl.org/perlfaq6.html#How-do-I-substitute-case-insensitively-on-the-LHS-while-preserving-case-on-the-RHS%3f

Doing this in two steps is probably a better / simpler idea ...

Using google power, I found this

 The :samecase modifier, short :ii (since it a variant of :i) preserve case. my $x = 'Abcd'; $x ~~ s:ii/^../foo/; say $x; # Foocd $x = 'ABC' $x ~~ s:ii/^../foo/; say $x # FOO This is very useful if you want to globally rename your module Foo, to Bar, but for example in environment variables it is written as all uppercase. With the :ii modifier the case is automatically preserved. 
+2
source

All Articles