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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Compiling a Pattern once as a static constant avoids re-parsing the regex on every call.
- 2Two alternations let a single regex handle both normal boundaries and acronym-to-word transitions.
- 3appendReplacement plus appendTail rebuild a string while touching only the matched regions.
Related explainers
rust
use once_cell::sync::Lazy; use regex::Regex; static NON_ALPHANUMERIC: Lazy<Regex> = Lazy::new(|| Regex::new(r"[^a-z0-9]+").unwrap());
Building URL slugs in Rust
string-processing
regex
transliteration
Intermediate
8 steps
java
@Component public class RegionCacheWarmer implements SmartInitializingSingleton { private static final Logger log = LoggerFactory.getLogger(RegionCacheWarmer.class);
Warming a Spring cache at startup
caching
startup-hook
dependency-injection
Intermediate
7 steps
python
import pandas as pd import numpy as np
Cleaning a customer DataFrame with pandas
data-cleaning
regex
normalization
Intermediate
9 steps
java
public final class EmailNormalizer { private static final Pattern EMAIL_PATTERN = Pattern.compile( "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
Normalizing email addresses in Java
validation
regex
normalization
Intermediate
8 steps
java
@RestController @RequestMapping("/api/products") @RequiredArgsConstructor public class ProductBatchController {
Batch JSON Merge Patch in Spring
json-merge-patch
rest-api
partial-update
Intermediate
8 steps
java
public class TimedFetchService { private final ExecutorService executor = Executors.newFixedThreadPool(8); private final HttpClient httpClient = HttpClient.newHttpClient();
Enforcing HTTP timeouts with a Future
concurrency
timeouts
thread-pool
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/converting-camelcase-to-snake_case-in-java-explained-java-3220/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.