How to convert camelCase to snake_case and back
Short answer
Insert an underscore before every capital letter that follows a lower case letter or a digit, then lowercase everything:
void main() {
String name = "userFirstName";
IO.println(name.replaceAll("([a-z0-9])([A-Z])", "$1_$2").toLowerCase());
}Output:
user_first_nameAbbreviations
For names like parseHTTPResponse, add a second rule — between an abbreviation and the next word:
String toSnake(String name) {
return name.replaceAll("([A-Z]+)([A-Z][a-z])", "$1_$2")
.replaceAll("([a-z0-9])([A-Z])", "$1_$2")
.toLowerCase();
}
void main() {
IO.println(toSnake("parseHTTPResponse"));
IO.println(toSnake("orderId2Value"));
}Output:
parse_http_response
order_id2_valueBack to camelCase
Split by underscores and capitalize the first letter of every part except the first one:
String toCamel(String name) {
String[] parts = name.split("_");
var result = new StringBuilder(parts[0]);
for (int i = 1; i < parts.length; i++) {
result.append(Character.toUpperCase(parts[i].charAt(0))).append(parts[i].substring(1));
}
return result.toString();
}
void main() {
IO.println(toCamel("user_first_name"));
}Output:
userFirstNameCommon mistake
Inserting an underscore before every capital letter unconditionally. Then a name starting with a capital gets a leading _, and an abbreviation falls apart into letters:
void main() {
IO.println("UserID".replaceAll("([A-Z])", "_$1").toLowerCase());
}Output:
_user_i_dFunctions used in this recipe
- String.replaceAll() — Replaces every match of a regular expression.
- String.toLowerCase() — Returns a copy of the string with all letters in lower case.
- String.split() — Splits a string into an array of parts by a separator.