in reply to change case

You want the ucfirst function, possibly applied word by word.

Lets say you have a string where you want to ucfirst each word. You could do that with the following:

$string = s/\b(\w+)\b/ucfirst($1)/eg;

You could modify the above regexp to handle apostrophes and hyphens by using negative lookbehind:

$string = s/(?<![-'])\b(\w+)\b/ucfirst($1)/eg;

The above substitution regex will apply ucfirst to any cluster of "word" characters as long as they're not immediately preceeded by an apostrophe or a hyphen. That way you don't end up with Frank'S Place when you really want Frank's Place.

Negative lookbehind with a character class is the right tool, as opposed to positive lookbehind for a negated character class, because you only care that an apostrophe or hyphen doesn't appear before the 'word' cluster. A negated character class inside of a positive lookbehind would require that a "non-apostrophe, non-hyphen" exist in front of the word cluster, which is going to foul everything up. You don't want that. ;)


Dave


"If I had my life to live over again, I'd be a plumber." -- Albert Einstein

Replies are listed 'Best First'.
Re: Re: change case
by sauoq (Abbot) on Nov 26, 2003 at 06:15 UTC

    You can skip the /e modifier by using the \u escape. And you don't need to capture the whole word; the first letter will do.

    perl -ple 's/\b(?<![-'])(\w)/\u$1/g'

    -sauoq
    "My two cents aren't worth a dime.";