• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 589
  • Last Modified:

Writing a regex for IntiCap of a String?

I have to build a utility where I want to do a InitCap on any arbitrary String the user passes.

I looked up all the solution on google seem to be doing it with loops etc. I want to use regex.

Nee help with this .. Example String is "    hello world 12ab AAA   ".

I want to preserve the leading and trailing spaces.

Thanx again.

  • 3
1 Solution
>> I want to use regex.
Java standard regexp don't have (like perl) the ability to use something similar to \U or \C to upper case what after.
If you use Jakarta ORO which supports a more like perl regexp then you can do that using the above.
If you are ok with downloading and using Jakarta ORO (http://jakarta.apache.org/oro/) then the syntax should be similar to this perl regexp:

$a="    hello world 12ab AAA   ";
print $a;

result:     Hello World 12ab AAA
You could do this with java.util.regex package:

                  String s = "    hello world 12ab AAA   ";
                  Pattern p = Pattern.compile("\\s*?(\\w)");
                  Matcher m = p.matcher(s);
                  if (m.find()) {
                        int end = m.end();
                        StringBuffer sb = new StringBuffer(s);
                        sb.setCharAt(end - 1, Character.toUpperCase(s.charAt(end - 1)));
Not sure how the above will do the job.
If you didn't expect for one regular expression that will do the job (as I mentioned above) and you are ok with code then you can use this code:

String s = "    hello world 12ab AAA   ";
Pattern p = Pattern.compile("(\\s*)([^\\s]+)");
Matcher m = p.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()) {
      String replaceWith = m.group(1) + Character.toUpperCase(m.group(2).charAt(0)) + m.group(2).substring(1);
                 m.appendReplacement(sb, replaceWith);

System.out.println(":" + sb + ":");

java Main
:    Hello World 12ab AAA   :

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now