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'
Perl: Use s/ (replace) and return new string [duplicate]
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.
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.
$1 equals the text " brown ".
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.
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