substituting words and maintaining case?

A

Art Merkel

I'd appreciate any suggestions for writing a function for substituting
words in a string but keeping the case the same, so for example,
starting with

Cats are furry. I like cats. Do you like CATS?

and the substitution cats -> kittens I'd like to get

Kittens are furry. I like kittens. Do you like KITTENS?

the way the Emacs replace command works.

thanks
 
J

John W. Krahn

Art said:
I'd appreciate any suggestions for writing a function for substituting
words in a string but keeping the case the same, so for example,
starting with

Cats are furry. I like cats. Do you like CATS?

and the substitution cats -> kittens I'd like to get

Kittens are furry. I like kittens. Do you like KITTENS?

perldoc -q "How do I substitute case insensitively on the LHS while preserving
case on the RHS"



John
 
T

Tad McClellan

Art Merkel said:
I'd appreciate any suggestions for writing a function for substituting
words in a string but keeping the case the same, so for example,
starting with

Cats are furry. I like cats. Do you like CATS?

and the substitution cats -> kittens I'd like to get

Kittens are furry. I like kittens. Do you like KITTENS?

the way the Emacs replace command works.


----------------------------
#!/usr/bin/perl
use warnings;
use strict;

$_ = "Cats are furry. I like cats. Do you like CATS?\n";
case_replace($_, 'caTS', 'kiTTens');
print;

sub case_replace {
my(undef, $pat, $rep) = map lc, @_;

$_[0] =~ s/\b($pat)\b/$rep/g;

s/(.)/\u$1/ for $pat, $rep;
$_[0] =~ s/\b($pat)\b/$rep/g;

s/(.+)/\U$1/ for $pat, $rep;
$_[0] =~ s/\b($pat)\b/$rep/g;
}
 
A

Art Merkel

Tad McClellan said:
#!/usr/bin/perl
use warnings;
use strict;

$_ = "Cats are furry. I like cats. Do you like CATS?\n";
case_replace($_, 'caTS', 'kiTTens');
print;

sub case_replace {
my(undef, $pat, $rep) = map lc, @_;

$_[0] =~ s/\b($pat)\b/$rep/g;

s/(.)/\u$1/ for $pat, $rep;
$_[0] =~ s/\b($pat)\b/$rep/g;

s/(.+)/\U$1/ for $pat, $rep;
$_[0] =~ s/\b($pat)\b/$rep/g;
}

Thanks!
 
A

Art Merkel

John W. Krahn said:
perldoc -q "How do I substitute case insensitively on the LHS while preserving
case on the RHS"

I thought my question was really weird, so it didn't occur to me
that it would be documented!

Thanks for the very polite RTFM.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,662
Latest member
sxarexu

Latest Threads

Top