user8372165
user8372165

Reputation:

Perl: regex substitution with case-sensitive backreference

Can you help me find a perl one-liner that can do a find/replace as follows:

Find: asomestring Replace: bsomestring

Find: Asomestring Replace: Bsomestring

essentially need to somehow backreference what case the original text was and replace it with different text, but same case. (case backreference for just the first character)

Thanks!!

Upvotes: 0

Views: 283

Answers (1)

ikegami
ikegami

Reputation: 385764

s/([mM])ark/ ( $1 eq 'm' ? 'j' : 'J' ) . 'oseph' /eg

or

my %repl = (
   'mark' => 'joseph',
   'Mark' => 'Joseph',
);

my $pat = join '|', map quotemeta, keys %repl;
my $re = qr/$pat/;

s/($re)/$repl{$1}/g;

Upvotes: 2

Related Questions