java 26 lines · 7 steps

Converting camelCase to snake_case in Java

A regex that spots case boundaries turns camelCase identifiers into snake_case with underscores.

Explained by highlit
1public final class CaseConverter {
2 
3 private static final Pattern CAMEL_BOUNDARY =
4 Pattern.compile("([a-z0-9])([A-Z])|([A-Z]+)([A-Z][a-z])");
5 
6 private CaseConverter() {
7 }
8 
9 public static String toSnakeCase(String camelCase) {
10 if (camelCase == null || camelCase.isEmpty()) {
11 return camelCase;
12 }
13 
14 Matcher matcher = CAMEL_BOUNDARY.matcher(camelCase);
15 StringBuilder result = new StringBuilder();
16 while (matcher.find()) {
17 String replacement = matcher.group(1) != null
18 ? matcher.group(1) + "_" + matcher.group(2)
19 : matcher.group(3) + "_" + matcher.group(4);
20 matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));
21 }
22 matcher.appendTail(result);
23 
24 return result.toString().toLowerCase(Locale.ROOT);
25 }
26}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Compiling a Pattern once as a static constant avoids re-parsing the regex on every call.
  2. 2Two alternations let a single regex handle both normal boundaries and acronym-to-word transitions.
  3. 3appendReplacement plus appendTail rebuild a string while touching only the matched regions.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Converting camelCase to snake_case in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code