PDA

View Full Version : capitalizing variables for display



cedsn
08-10-2002, 01:53 AM
I'm sure this is something simple, but as I'm a bit new to regular expressions, it's giving me a headache.

what i want to do is take a character string of varying lengths of words and capitalize every word.. i have so far suceeded in taking of the first letter and lowercasing the rest as follows:

$brand =~ s/\w//;
$brand =~ tr/A-Z/a-z/;

and i assume there must be some way to put the first character in another variable and capitalize it, then put them back together.. but most likely i'm going about it all wrong. Can anyone tell me the easy way to do this?

thanks, jesse

Mouldy_Goat
08-10-2002, 05:26 AM
Haven't tested this but something like this:

$data =~ s/\b(\w)/\U$1/g;
Should do the trick I think...

cedsn
08-10-2002, 06:22 AM
that did it!

first i had to lowercase everything with

$data =~ tr/A-Z/a-z/;

then user your snippet there and worked like a charm.

thanks!

Mouldy_Goat
08-10-2002, 07:25 PM
By the way, there's a command lc() which returns the lowercase version of its argument.. so you could use:
$data = lc($data);
instead.. not sure that it makes too much difference.

mtm
10-28-2003, 02:43 AM
This is an old thread, but the same problem..
I need any input of any length returned as first-letter-of-the-word-capitalized. As This Is...
<br>

I agree the idea to make all lowercase first is ideal!
but, what is the $data =~ tr/A-Z/a-z/; doing?

<br>
ans in the following...$data =~ s/\b(\w)/\U$1/g;
could you just treat me to an explanation as I'm a tad confused now.
<br>
Also, when the g or i or m is used, which way is it?
quotations? not? If there is a replace() function , then the g,m, or i goes out of the parens, or inside it?
<br>
Yes, I am reading tons of examples and getting crazy!

Many thanks...

cedsn
11-03-2003, 06:46 PM
i'm no regular expressions expert, but i can offer a little explanantion.


but, what is the $data =~ tr/A-Z/a-z/; doing?

[tr]anslating any character in the A-Z set of capital letters to its corresponding lowercase character.. or in other words,

tr/target set/replacement set/;


ans in the following...$data =~ s/\b(\w)/\U$1/g;

s = substitute

\b = border so it's looking for a word border
\w = word charachter (like a letter).. since it's in parentheses that means we can refer to this match later in the replacement area..

\U means to uppercase it
$1 refers to the match we found in parentheses, if there were multiple parenteses in our target pattern they would be referred to as $2, $3, etc

then the g; modifier means global, so it searches and replaces every match it can, the i modifier i think has to do with case, not sure about m, but i do know the modifier goes at the end. hope this helps, and there is plenty of info on regular expressions out there to look up though i find it pretty confusing.