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.

Who is Participating?
aozarovConnect With a Mentor Commented:
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   :
>> 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)));
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.