Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Is there a reg exp to replace something like 'cat Cat' to 'dog Dog'?
  • Comment on case insensitive replace, but maintains capitalization

Replies are listed 'Best First'.
Re: case insensitive replace, but maintains capitalization
by Anonyrnous Monk (Hermit) on Dec 24, 2010 at 05:10 UTC

    Maybe this is what you mean — i.e. replace (for example) 'cat' with 'dog', but only if 'Cat' is capitalized, the replacement word should also be capitalized, otherwise not (?)

    #!/usr/bin/perl -wl use strict; my %repl = ( cat => 'dog', foo => 'bar', ); sub repl { my $word = shift; my $lookup = lc $word; return $word unless exists $repl{$lookup}; # nothing to replace my $is_up = $word =~ /^[[:upper:]]/; # determine caps style my $repl = $repl{$lookup}; $repl = ucfirst $repl if $is_up; # apply caps style return $repl; } my $s = 'cat Cat foo Foo Blah blub'; $s =~ s/\b(\w+)\b/repl($1)/eg; print $s; # dog Dog bar Bar Blah blub

    This could also be extended to handle all-uppercase words, too, or in theory any cOMbinatION, in which case the source and replacement word would have to have the same length, though.

      Bingo!! This is exactly what I wanted!!

        This script beautifully handles the first letter of the word. You'll still have to define the (complex) rules for this in case you need more than just first letter. For example if you want "animal" to be replaced by "pet" then what should "ANiMal" be replaced with?

        -- Regards - Samar
Re: case insensitive replace, but maintains capitalization
by jwkrahn (Abbot) on Dec 24, 2010 at 08:41 UTC
Re: case insensitive replace, but maintains capitalization
by ikegami (Patriarch) on Dec 24, 2010 at 05:28 UTC
    You want cat to become Cat, and you want dog to become Dog? ucfirst!
Re: case insensitive replace, but maintains capitalization
by ikegami (Patriarch) on Dec 24, 2010 at 04:27 UTC
    Regular expressions are patterns that can be matched. They don't do anything, much less replace anything. You could use the substitution operator. It uses a regular expression to determine what to replace.
    s/cat Cat/dog Dog/
      Sorry, I should be more specific, I need a generic reg exp taht can handle all words. The 'cat' word is just an example, it could be anything else.

        You're in luck, /\w+/ is a regular expression that can handle all words!

        ...roboticus

        Mr. Tautology

        </snark-mode>

        so use \w+
Re: case insensitive replace, but maintains capitalization
by Anonymous Monk on Dec 24, 2010 at 04:26 UTC
    Almost, you can do it with the substitution operator
    $_ = 'blah Blah'; s/blah Blah/dog Dog/; print $_; __END__ dog Dog
    perlintro, perlretut