简体   繁体   中英

Regex replace space and word to toFirstUpper of word

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 .

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM