dragostis
dragostis

Reputation: 2662

Replace capital letter with underscore + lowercase letter in Java?

Is there a way to use RegEx in Java to replace all capital letters with an underscore and the same letter only lowercase?

Example: getSpecialString -> get_special_string

Upvotes: 10

Views: 18562

Answers (3)

Austin Mayer
Austin Mayer

Reputation: 11

This could also work using Regex!

"MyCamelCase".replaceAll(/(?<!^)[A-Z]/g, (match) => `_${match}`).toLowerCase();

Upvotes: 1

Valentyn Kolesnikov
Valentyn Kolesnikov

Reputation: 2097

There is a snakeCase method in underscore-java library:

import com.github.underscore.U;

public class Main {

    public static void main(String[] args) {
        U.snakeCase("getSpecialString"); // -> get_special_string
    }
}

Upvotes: 0

hsz
hsz

Reputation: 152216

Just try with:

"getSpecialString".replaceAll("([A-Z])", "_$1").toLowerCase();

Upvotes: 46

Related Questions