简体   繁体   English

如何验证字符串是否是有效的java变量?

[英]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? 如何最好地检查字符串输入是否是用于编码的有效java变量? 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: 最好的可能是RegEx,它检查:

  • 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. 编辑:并且,如@Joey所示,您还应该过滤掉关键字和保留字。

Just use the built-in isName method: 只需使用内置的isName方法:

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. 请参阅isName()文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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