简体   繁体   中英

How to validate if a string would be a valid java variable?

How can I best check if a string input would be a valid java variable for coding? I'm sure I'm not the first one who is willing to do this. But maybe I'm missing the right keyword to find something useful.

Best would probably be a RegEx, which checks that:

  • starts with a letter

  • can then contain digits, letters

  • can contain some special characters, like '_' (which?)

  • may not contain a whitespace separator
public static boolean isValidJavaIdentifier(String s) {
    if (s.isEmpty()) {
        return false;
    }
    if (!Character.isJavaIdentifierStart(s.charAt(0))) {
        return false;
    }
    for (int i = 1; i < s.length(); i++) {
        if (!Character.isJavaIdentifierPart(s.charAt(i))) {
            return false;
        }
    }
    return true;
}

EDIT: and, as @Joey indicates, you should also filter out keywords and reserved words.

Just use the built-in isName method:

public static boolean isName(CharSequence name)

This returns whether or not a name is a syntactically valid qualified name in the latest source version.

See the isName() documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM