Gabriel Ortega Rosero Gabriel Ortega Rosero - 1 month ago 10
Java Question

How do I convert a camelCase string to underscore in java keeping some upper cases and the rests as lower cases?

How do I convert a camel case string to underscore in java keeping some upper case letters? I'm usin this code:

String inputString = "Hi How areYouToday";
String result = inputString.replaceAll("([a-z])([A-Z]+)", "$1_$2");


I can convert inputString in
Hi How are_You_Today
, but, I need to get
Hi How are_you_today
.

Notice that only converted part is changed to lower case version.

Answer

You can use Matcher#appendReplacement and pass dynamic result of replacement, based on what was found by regex.

I also changed your regex a little bit, to not include lowercase part in match, but accept only uppercase characters which are preceded by lowercase character. More info at: http://www.regular-expressions.info/lookaround.html

String text = "Hi How areYouToday";
Matcher m = Pattern.compile("(?<=[a-z])[A-Z]").matcher(text);

StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, "_"+m.group().toLowerCase());
}
m.appendTail(sb);

System.out.println(sb.toString()); //Hi How are_you_today