Java验证含空格的用户名


1.Java验证用户名的正则表达式

  1. @Test  
  2. public void formalRegex() {  
  3.     String str = "123+123";  
  4.       
  5.     Pattern pattern = Pattern.compile("[0-9a-zA-Z\u4E00-\u9FA5]+");  
  6.     Matcher matcher = pattern.matcher(str);  
  7.       
  8.     if (!matcher.matches() ) {  
  9.         System.out.println("不满足条件");  
  10.     } else {  
  11.         System.out.println("满足正则式");  
  12.     }  
  13. }  
这是一般的用户名验证,这种验证是要求用户名不能有空格的

今天遇到了比较麻烦的问题,用户名允许有空格......

在允许有空格的情况下要注意把"\n"等特殊的字符给过滤掉,于是采用下面的代码

  1. @Test  
  2. public void spaceRegex() {  
  3.     String str = "123\n 123";  
  4.       
  5.     Pattern pattern = Pattern.compile("[0-9a-zA-Z\u4E00-\u9FA5\\s]+");  
  6.     Matcher matcher = pattern.matcher(str);  
  7.       
  8.     Pattern special = Pattern.compile("\\s*|\t|\r|\n");   
  9.     Matcher specialMachter = special.matcher(str);  
  10.       
  11.     if (!matcher.matches() || !specialMachter.matches()) {  
  12.         System.out.println("不满足条件");  
  13.     } else {  
  14.         System.out.println("满足正则式");  
  15.     }  
  16. }  
使用两遍正则验证,换行制表等特殊字符就被过滤掉了

相关内容