开发者

Perl regex replace in same case

If you have a simple regex replace in perl as follows:

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

how would I modify it so that it looks at the match and makes the replacement the same case as the match开发者_Python百科 for example:

'JAM' would become 'AAA' and 'jam' would become 'aaa'


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 unhandled characters resp. their categories are a bit easier to see than in the other answers.


In Perl 5 you can do something like:

$line =~ s/JAM/$_=$&; tr!A-Z!A!; tr!a-z!a!; $_/gie;

It handles all different cases of JAM, like Jam, and it's easy to add other words, eg:

$line =~ s/JAM|SPAM/$_=$&; tr!A-Z!A!; tr!a-z!a!; $_/gie;


Something like this perhaps?

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

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

Using the power of google I found this

The :samecase modifier, short :ii (since it's 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.


$line =~ s/JAM/{$& eq 'jam' ? 'aaa' : 'AAA'}/gie;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜