歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java驗證含空格的用戶名

Java驗證含空格的用戶名

日期:2017/3/1 11:10:22   编辑:Linux編程

1.Java驗證用戶名的正則表達式

  1. @Test
  2. public void formalRegex() {
  3. String str = "123+123";
  4. Pattern pattern = Pattern.compile("[0-9a-zA-Z\u4E00-\u9FA5]+");
  5. Matcher matcher = pattern.matcher(str);
  6. if (!matcher.matches() ) {
  7. System.out.println("不滿足條件");
  8. } else {
  9. System.out.println("滿足正則式");
  10. }
  11. }
這是一般的用戶名驗證,這種驗證是要求用戶名不能有空格的

今天遇到了比較麻煩的問題,用戶名允許有空格......

在允許有空格的情況下要注意把"\n"等特殊的字符給過濾掉,於是采用下面的代碼

  1. @Test
  2. public void spaceRegex() {
  3. String str = "123\n 123";
  4. Pattern pattern = Pattern.compile("[0-9a-zA-Z\u4E00-\u9FA5\\s]+");
  5. Matcher matcher = pattern.matcher(str);
  6. Pattern special = Pattern.compile("\\s*|\t|\r|\n");
  7. Matcher specialMachter = special.matcher(str);
  8. if (!matcher.matches() || !specialMachter.matches()) {
  9. System.out.println("不滿足條件");
  10. } else {
  11. System.out.println("滿足正則式");
  12. }
  13. }
使用兩遍正則驗證,換行制表等特殊字符就被過濾掉了
Copyright © Linux教程網 All Rights Reserved