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?
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("_"));
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With