Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PaseclCase String to Uppercase separated by underscore [duplicate]

Tags:

java

What's the best way to convert a "PascelCase" string to all upper case separated by underscore like "Pascel_CASE". I wrote this code which works:

  private static String pascelCaseToUpperCaseSeparatedByUnderscore(String s) {
        
        String[] values = s.split("(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])");
        
        for (int i = 0, len = values.length; i < len; i++) {
            values[i] = values[i].toUpperCase();
        }
        return String.join("_", values);
    }

However, is there better way say, using a library, to do this?

like image 616
Heisenberg Avatar asked Apr 07 '26 19:04

Heisenberg


2 Answers

Your regex looks complicated at first glance, which might discourage other people who read your code and are not familiar with regex. You can replace it with this more compact and readable one:

"(?=\\p{Upper})"

and in connection with streams this one-liner reads almost like plain text

private static String camelCaseToUpperCaseSeparatedByUnderscore(String s) {
    return Pattern.compile("(?=\\p{Upper})")
                  .splitAsStream(s)
                  .map(String::toUpperCase)
                  .collect(Collectors.joining("_"));
}
like image 97
Eritrean Avatar answered Apr 09 '26 09:04

Eritrean


If you can use Guava you can do:

String camelCase = "CamelCase";

String underscore = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, camelCase);

System.out.println(underscore);

If you just want to use regex you can do:

String underscore = String.join("_", Arrays.asList(camelCase.split("(?=[A-Z])")).stream()
    .map(String::toUpperCase).collect(Collectors.toList()));

You can also use Arrays.stream() instead:

String underscore = Arrays.stream(camelCase.split("(?=[A-Z])")).map(String::toUpperCase)
            .collect(Collectors.joining("_"));

Output

CAMEL_CASE
like image 39
Oboe Avatar answered Apr 09 '26 09:04

Oboe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!