Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to valid Java variable name

For a code generation tool I'm working on, I need to take a string and generate a valid java variable name from it, but I'm not sure about the best way to do it.

For example:

"123 this is some message !" => _123_this_is_some_message ( or something similar)

Thanks

like image 673
Hugo Zapata Avatar asked Oct 05 '12 21:10

Hugo Zapata


1 Answers

Assuming you replace all invalid characters by _ something like the code below could work (rough example). You might want to add some logic for name collisions etc. It is based on the JLS #3.8:

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter.
[...]
A "Java letter" is a character for which the method Character.isJavaIdentifierStart(int) returns true.
A "Java letter-or-digit" is a character for which the method Character.isJavaIdentifierPart(int) returns true.

public static void main(String[] args) {
    String s = "123 sdkjh s;sdlkjh d";
    StringBuilder sb = new StringBuilder();
    if(!Character.isJavaIdentifierStart(s.charAt(0))) {
        sb.append("_");
    }
    for (char c : s.toCharArray()) {
        if(!Character.isJavaIdentifierPart(c)) {
            sb.append("_");
        } else {
            sb.append(c);
        }
    }

    System.out.println(sb);
}
like image 87
assylias Avatar answered Sep 27 '22 23:09

assylias