in reply to Case-preserving regexp search and replace?

I'd suggest checking perlfaq6, question five. I added a solution to it, which will appear in some future Perl:
$_ = "this is a TEsT case"; s/(test)/preserve_case($1, "success")/egi; sub preserve_case { my ($from, $to) = @_; my ($lf, $lt) = map length, @_; if ($lt < $lf) { $from = substr $from, 0, $lt } else { $from .= substr $to, $lf } return uc $to | ($from ^ uc $from); }

_____________________________________________________
Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Replies are listed 'Best First'.
Re: Re: Case-preserving regexp search and replace?
by rrwo (Friar) on Aug 31, 2001 at 08:33 UTC

    I tried it, and it doesn't work as needed: I need it to match the case of the last letter. So if I want to replace "FOOBAR" with "whatever", it will return "WHATEVer" instead of "WHATEVER".

    Newever versions of the Regexp FAQ have some routines not online here that do that fiddling with bits in ASCII. Not necessarily Unicode compliant but neat tricks nontheless.

      If you want to keep the case of the last letter, then the other solution in perlfaq6 is what you want.

      _____________________________________________________
      Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
      s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;