判断java标识符
1 package com.jdk7.chapter5; 2 3 public class JavaIdentifier { 4 5 /** 6 * 使用Character.isJavaIdentifierPart判断字符是否属于java标识符 7 it is a letter 8 it is a currency symbol (such as '$') 9 it is a connecting punctuation character (such as '_') 10 it is a digit 11 it is a numeric letter (such as a Roman numeral character) 12 it is a combining mark 13 it is a non-spacing mark 14 '\u005Cu0000' through '\u005Cu0008' 15 '\u005Cu000E' through '\u005Cu001B' 16 '\u005Cu007F' through '\u005Cu009F' 17 * @param str 18 * @return 19 */ 20 public static boolean isJavaIdentifier(String str){ 21 if(str==null || str.length()==0){ 22 return false; 23 } 24 char[] ch = str.toCharArray(); 25 for(int i=0;i<ch.length;i++){ 26 if(!(Character.isJavaIdentifierPart(ch[i]))){ 27 return false; 28 } 29 } 30 return true; 31 } 32 33 public static void main(String[] args) { 34 System.out.println("my_var is an identifier? "+JavaIdentifier.isJavaIdentifier("my_var")); 35 System.out.println("$my_var is an identifier? "+JavaIdentifier.isJavaIdentifier("$my_var")); 36 System.out.println("my_var.1 is an identifier? "+JavaIdentifier.isJavaIdentifier("my_var.1")); 37 System.out.println("1$my_var is an identifier? "+JavaIdentifier.isJavaIdentifier("1$my_var")); 38 System.out.println("u0391var is an identifier? "+JavaIdentifier.isJavaIdentifier("u0391var")); 39 System.out.println("null is an identifier? "+JavaIdentifier.isJavaIdentifier(null)); 40 System.out.println("null is an identifier? "+JavaIdentifier.isJavaIdentifier(" ")); 41 } 42 } 43 44 45 执行结果: 46 my_var is an identifier? true 47 $my_var is an identifier? true 48 my_var.1 is an identifier? false 49 1$my_var is an identifier? true 50 u0391var is an identifier? true 51 null is an identifier? false 52 null is an identifier? false