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
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);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With