CaseUtils { public static String toSnakeCase(String word) { if (StringUtils.isEmpty(word)) { return word; } String firstPattern = "([A-Z]+)([A-Z][a-z])"; String secondPattern = "([a-z\\d])([A-Z])"; String replacementPattern = "$1_$2"; word = word.replaceAll(firstPattern, replacementPattern); word = word.replaceAll(secondPattern, replacementPattern); word = word.replaceAll("(\\s|-)", "_"); word = word.toLowerCase(Locale.US); return word; } private  CaseUtils(); static String snakeToPascalCase(String str); static String snakeToCamelCase(String str); static String toCamelCase(String str); static String toPascalCase(String str); static String toCamelCase(String str, final boolean capitalizeFirstLetter, final char... delimiters); static String toSnakeCase(String word);  }
@Test public void convertsToSnakeCase() { assertThat(CaseUtils.toSnakeCase("foo"), equalTo("foo")); assertThat(CaseUtils.toSnakeCase(" foo"), equalTo("_foo")); assertThat(CaseUtils.toSnakeCase(" fooBar"), equalTo("_foo_bar")); assertThat(CaseUtils.toSnakeCase("10-foo"), equalTo("10_foo")); assertThat(CaseUtils.toSnakeCase("_foo"), equalTo("_foo")); assertThat(CaseUtils.toSnakeCase("FooBar"), equalTo("foo_bar")); assertThat(CaseUtils.toSnakeCase("FooAPI"), equalTo("foo_api")); assertThat(CaseUtils.toSnakeCase("Ec2Foo"), equalTo("ec2_foo")); assertThat(CaseUtils.toSnakeCase("foo_bar"), equalTo("foo_bar")); }