亚洲av成人无遮挡网站在线观看,少妇性bbb搡bbb爽爽爽,亚洲av日韩精品久久久久久,兔费看少妇性l交大片免费,无码少妇一区二区三区

Chinaunix

標題: java驗證用戶名長度的正則表達式使用 [打印本頁]

作者: zhaozy78    時間: 2015-07-07 11:09
標題: java驗證用戶名長度的正則表達式使用
用戶名可能包含中文,中文按2位算
源碼下載地址:http://www.zuidaima.com/share/1550463222516736.htm

驗證用戶名,支持中英文(包括全角字符)、數(shù)字、下劃線和減號 (全角及漢字算兩位),長度為4-20位,中文按二位計數(shù)
  1. package com.zuidaima.regularexpression;

  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;

  4. public class UserReg {
  5.     /**
  6.      * 驗證用戶名,支持中英文(包括全角字符)、數(shù)字、下劃線和減號 (全角及漢字算兩位),長度為4-20位,中文按二位計數(shù)
  7.      * @author www.zuidaima.com
  8.      * @param userName
  9.      * @return
  10.      */
  11.     public static boolean validateUserName(String userName) {
  12.         String validateStr = "^[\\w\\--_[0-9]\u4e00-\u9fa5\uFF21-\uFF3A\uFF41-\uFF5A]+$";
  13.         boolean rs = false;
  14.         rs = matcher(validateStr, userName);
  15.         if (rs) {
  16.             int strLenth = getStrLength(userName);
  17.             if (strLenth < 4 || strLenth > 20) {
  18.                 rs = false;
  19.             }
  20.         }
  21.         return rs;
  22.     }

  23.     /**
  24.      * 獲取字符串的長度,對雙字符(包括漢字)按兩位計數(shù)
  25.      *
  26.      * @param value
  27.      * @return
  28.      */
  29.     public static int getStrLength(String value) {
  30.         int valueLength = 0;
  31.         String chinese = "[\u0391-\uFFE5]";
  32.         for (int i = 0; i < value.length(); i++) {
  33.             String temp = value.substring(i, i + 1);
  34.             if (temp.matches(chinese)) {
  35.                 valueLength += 2;
  36.             } else {
  37.                 valueLength += 1;
  38.             }
  39.         }
  40.         return valueLength;
  41.     }

  42.     private static boolean matcher(String reg, String string) {
  43.         boolean tem = false;
  44.         Pattern pattern = Pattern.compile(reg);
  45.         Matcher matcher = pattern.matcher(string);
  46.         tem = matcher.matches();
  47.         return tem;
  48.     }

  49.     public static void main(String[] args) {
  50.         String str = "0-_f9zd中22";
  51.         String st = "A-dq_!!。∪シ枠颂!ノチセたのひちぬ!當然。!!..**半角";

  52.         System.out.println(validateUserName(str));
  53.         System.out.println(st.replaceAll("[\\pP&&[^-_]]", ""));
  54.         System.out.println(st.replaceAll("[\\w\\-一-龥A-Za-z]", ""));
  55.     }
  56. }

  57.                     
復(fù)制代碼





歡迎光臨 Chinaunix (http://72891.cn/) Powered by Discuz! X3.2