Regex for converting CamelCase to camel_case in java

By | August 6, 2019


I understand why the desired output is not given for converting using regex a string like FooBar to Foo_Bar which instead gives Foo_Bar_. I could have done something with String.substring substring(0, string.length() - 2) or just replaced the last character, but I think there is a better solution to such a scenario.

Here is the code:

String regex = "([A-Z][a-z]+)";
String replacement = "$1_";

"CamelCaseToSomethingElse".replaceAll(regex, replacement); 

outputs: Camel_Case_To_Something_Else_
desired output: Camel_Case_To_Something_Else

Question: Looking for a neater way to get the desired output?


See this question and CaseFormat from guava

in your case, something like:, "SomeInput");

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *