黑马程序员技术交流社区

标题: 弄了个验证用户名长度正则表达式,大家看看有什么问题? [打印本页]

作者: 李能甫    时间: 2015-3-30 09:10
标题: 弄了个验证用户名长度正则表达式,大家看看有什么问题?
  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;

  3. public class UserReg {
  4.     /**
  5.      * 验证用户名,支持中英文(包括全角字符)、数字、下划线和减号 (全角及汉字算两位),长度为4-20位,中文按二位计数
  6.      * @author www.zuidaima.com
  7.      * @param userName
  8.      * @return
  9.      */
  10.     public static boolean validateUserName(String userName) {
  11.         String validateStr = "^[\\w\\--_[0-9]\u4e00-\u9fa5\uFF21-\uFF3A\uFF41-\uFF5A]+$";
  12.         boolean rs = false;
  13.         rs = matcher(validateStr, userName);
  14.         if (rs) {
  15.             int strLenth = getStrLength(userName);
  16.             if (strLenth < 4 || strLenth > 20) {
  17.                 rs = false;
  18.             }
  19.         }
  20.         return rs;
  21.     }

  22.     /**
  23.      * 获取字符串的长度,对双字符(包括汉字)按两位计数
  24.      *
  25.      * @param value
  26.      * @return
  27.      */
  28.     public static int getStrLength(String value) {
  29.         int valueLength = 0;
  30.         String chinese = "[\u0391-\uFFE5]";
  31.         for (int i = 0; i < value.length(); i++) {
  32.             String temp = value.substring(i, i + 1);
  33.             if (temp.matches(chinese)) {
  34.                 valueLength += 2;
  35.             } else {
  36.                 valueLength += 1;
  37.             }
  38.         }
  39.         return valueLength;
  40.     }

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

  48.     public static void main(String[] args) {
  49.         String str = "0-_f9zd中22";
  50.         String st = "A-dq_!!!!去符号标号!ノチセたのひちぬ!当然。!!..**半角";

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

  56.                     
复制代码

作者: fantacyleo    时间: 2015-3-30 15:25
这是你自己弄出来的?做得不错




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2