Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 for example:

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

like image 341
ar.dll Avatar asked Jun 08 '11 14:06

ar.dll


People also ask

How do I replace a section of a string in Perl?

Perl: Use s/ (replace) and return new string [duplicate]

How do I change a pattern in Perl?

You can use $& to get everything matched by the regular expression. Show activity on this post. After the match, $1 contains the string op . The substitution than matches the op , but there are no parentheses in the search part, so $1 gets cleared, and there's nothing to substitute the op with.

What does =~ do in Perl?

Look it up on a text on Perl. Use parentheses. The ( =~ ) operator takes two arguments: a string on the left and a regular expression pattern on the right. Instead of searching in the string contained in the default variable, $_ , the search is performed in the string specified.

What is the meaning of $1 in Perl regex?

$1 equals the text " brown ".


1 Answers

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.

like image 196
daxim Avatar answered Sep 28 '22 09:09

daxim