File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Regex for Init Cap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Regex for Init Cap" Watch "Regex for Init Cap" New topic

Regex for Init Cap

Jennifer Moran
Ranch Hand

Joined: Oct 21, 2002
Posts: 60
Hi -

I wanted to Capitalize all first letters of a name (whether it's a proper name or company name etc). I was thinking instead of writing a function I could do it with a regexp but I am not that 'good' with regexp and was looking for advice. Should I use regexp or just code a function? If I use regexp could someone provide me with the details?


Henry Wong

Joined: Sep 28, 2004
Posts: 19925

If I use regexp could someone provide me with the details?

Regex is not a simple library -- it is argubly its own language. So... if you want to use regex, you need to just dive in and learn it. (Basically, get a book and learn it. It won't be wasted, as once you get the regex hammer into your toolbox, everything will start looking like a nail... )

Once you get started... take a look at the find(), appendReplacement(), and appendTail() methods. Basically, you need the regex to look for the beginning of the word that starts with a lower case character, and then convert them to upper case.

The standard regex replaceFirst() and replaceAll() methods don't support the conversion to uppercase (or any type of conversion), so you'll need to use the appendXXX() methods.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Jennifer Moran
Ranch Hand

Joined: Oct 21, 2002
Posts: 60
Thanks so much for the point in the right direction.

Much appreciated,

John de Michele

Joined: Mar 09, 2009
Posts: 600

Mastering Regular Expressions, 3ed is a very good book on the subject. It has good coverage of several languages' regex libraries, including Java.


Edit: fixed link
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 43343
John de Michele wrote:Jennifer,

Mastering Regular Expressions, 3ed . . .
Thank you, but there is an error in that link. This is a link to that same book in our book reviews. It was given 10 horseshoes. There is a link to Amazon from the review to purchase the book.
Rob Spoor

Joined: Oct 27, 2005
Posts: 20046

Campbell Ritchie wrote:It was given 10 horseshoes.

Oh great, another book I have to buy now! And I still have to finish two other books!

How To Ask Questions How To Answer Questions
Jennifer Moran
Ranch Hand

Joined: Oct 21, 2002
Posts: 60
I'll definitely check it out.

Thanks again!!

I agree. Here's the link:
subject: Regex for Init Cap
It's not a secret anymore!