Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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_name

Abbreviations

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_value

Back 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:

userFirstName

Common 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_d

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.