-1
public class Test {
    public static void main(String[] args) {
    String key = "camelCase01";
    System.out.println(caseFormat.LOWER_CAMEL.to(caseFormat.LOWER_UNDERSCORE, key));
    }
}

Output : camel_case01

But I want to print line camel_case_01

2 Answers2

1

Here's one way to do this.

Split the string into alpha and numeric values i.e. separate the numbers from the alphabets. See here - Java- Split String which is alphanumeric

Then, apply the snake_casing on all strings of alphabets and join the array with an "_"

him229
  • 1,284
  • 1
  • 11
  • 21
0

As Java does not seem to support case conversion using \l, you can try this method:

public static String toSnake(String s) {
        return s.replaceAll("([A-Z]|\\d+)", "_$1") // add _ before a cap letter or sequence of digits
                .replaceAll("_+", "_") // replace multiple underscores with one
                .replaceAll("^_", "")  // remove leading underscores
                .toLowerCase();
}

// Test
Arrays.asList(
    "camelCase01", "anotherCamelCase", "version1", 
    "version1_2", "PascalCase", "123SlySnake")
    .forEach(s -> System.out.println(s + " -> " + toSnake(s)));

Output

camelCase01 -> camel_case_01
anotherCamelCase -> another_camel_case
version1 -> version_1
version1_2 -> version_1_2
PascalCase -> pascal_case
123SlySnake -> 123_sly_snake
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42