4

Does anyone know of a library that would allow me to convert a camel case string to an uppercase with underscore string?

e.g. addressId ==> ADDRESS_ID

Justin Kredible
  • 8,354
  • 15
  • 65
  • 91
  • 1
    Regexes are your friend: http://stackoverflow.com/questions/3621464/camelcase-conversion-to-friendly-name-i-e-enum-constants-problems – Edward Dale Jun 29 '11 at 20:14

2 Answers2

6

You can create your own method:

public static String toUpperCaseWithUnderscore(String input) {
    if(input == null) {
        throw new IllegalArgumentException();
    }

    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < input.length(); i++) {
        char c = input.charAt(i);
        if(Character.isUpperCase(c)) {
            if(i > 0) {
                sb.append('_');
            }
            sb.append(c);
        } else {
            sb.append(Character.toUpperCase(c));
        }
    }

    return sb.toString();
}
The Scrum Meister
  • 29,681
  • 8
  • 66
  • 64
3

In one line:

s.replaceAll("(?=[A-Z])","_").toUpperCase();

This assumes an ASCII string, though. If you want full Unicode:

s.replaceAll("(?=[\\p{Lu}])","_").toUpperCase();

If you want to deal also with PascalCase (first uppper case letter) add a .replaceAll("^_","")

s.replaceAll("(?=[\\p{Lu}])","_").toUpperCase().replaceAll("^_","");
leonbloy
  • 73,180
  • 20
  • 142
  • 190