[英]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?) 可以包含一些特殊字符,比如'_'(哪个?)
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所示,您还应该过滤掉关键字和保留字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.