1. 程式人生 > >支援中文,字母,數字,長度大於1個漢字,小於20個字元

支援中文,字母,數字,長度大於1個漢字,小於20個字元


 public class Test {
    public static void main(String[] args) {
        String InputName = "我是 CSDN,";
        
        boolean result = checkInputName(InputName);
        
        if(!result){
        	
        	System.out.println("入住人格式錯誤請重新輸入!");
       	}

    }
    
    
    public static boolean isChineseChar(char c) {
    	return String.valueOf(c).matches("[\u4e00-\u9fa5]");
    }
    
    
    public static boolean checkInputName(String str){  
    	
    	if(str.length() < 2 || str.length() > 20){
    		
    		return false;
    		}
 			boolean isRight = true;
 			for (int i = 0; i < str.length(); i++){
 				
 				boolean isDigit = false,  isLetter = false, isChinses =false;
 				
 				if(isChineseChar(str.charAt(i))) {
 			 		
 			 		System.out.println("該字元是中文:" + str.charAt(i));  
 			 		isChinses = true;
 			 	}else if (Character.isDigit(str.charAt(i))){
 					
 					System.out.println("該字元是數字:" + str.charAt(i));   
 					isDigit = true; 
 			 	}else if (Character.isLetter(str.charAt(i))) {
 			 		
 			 		System.out.println("該字元是字母:" + str.charAt(i));  
 			 	   isLetter = true;  
 			 	}
 			 	
 			 	if(!isDigit && !isLetter && !isChinses){
 			 			System.out.println("該字元既不是數字、字母、中文:" + str.charAt(i));
 			 			isRight = false;
 			 			break;
 			 				
 			 	}
 			 	   
 			}  
 			 	   
			return isRight;
				
		} 

    
}