4

I was trying to use regex to change the following string

String input = "Creation of book orders" 

to

String output = "CreationOfBookOrders"

I tried the following expecting to replace the space and word with word.

input.replaceAll("\\s\\w", "(\\w)");
input.replaceAll("\\s\\w", "\\w");

but here the string is replacing space and word with character 'w' instead of the word.

I am in a position not to use any WordUtils or StringUtils or such Util classes. Else I could have replaced all spaces with empty string and applied WordUtils.capitalize or similar methods.

How else (preferably using regex) can I get the above output from input.

Philip John
  • 5,275
  • 10
  • 43
  • 68
  • Why are you not in position to use library functions ? –  Mar 20 '16 at 10:09
  • @noob I am trying to generate code using `xtext` and `xtend`. I am not sure why but I am not able to import any extra jars or dependencies. I am forced to use the basic Java methods configured in them – Philip John Mar 20 '16 at 10:11
  • 2
    In Notepad++ you could search for `\s(\w)` and replace with `\U$1` - not sure if java supports something similar. – Sebastian Proske Mar 20 '16 at 10:14
  • @SebastianProske I tried this in java. `replaceAll("\\s(\\w)","\\U$1")` It is not working there. – Philip John Mar 20 '16 at 10:20
  • 1
    Yep, seems so - have a look [here](http://stackoverflow.com/questions/2770967/use-java-and-regex-to-convert-casing-in-a-string), maybe this helps – Sebastian Proske Mar 20 '16 at 10:20

1 Answers1

2

I don't think you can do that with String.replaceAll. The only modifications that you can make in the replacement string are to interpolate groups matched by the regex.

The javadoc for Matcher.replaceAll explains how the replacement string is handled.

You will need use a loop. Here's a simple version:

StringBuilder sb = new StringBuilder(input);
Pattern pattern = Pattern.compile("\\s\\w");
Matcher matcher = pattern.matcher(s);
int pos = 0;
while (matcher.find(pos)) {
    String replacement = matcher.group().substring(1).toUpperCase();
    pos = matcher.start();
    sb.replace(pos, pos + 2, replacement);
    pos += 1;
}
output = sb.toString();

(This could be done more efficiently, but it is complicated.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216