验证用户名长度的正则表达式

来源:互联网 发布:公共卫生论文方向知乎 编辑:程序博客网 时间:2024/05/10 17:18

用户名可能包含中文,中文按2位算

代码下载地址:http://www.zuidaima.com/share/1550463222516736.htm

转载请注明出处:验证用户名长度的正则表达式

运行此代码截图如下:

 

满足此表达式:

不满足此表达式:

 

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.zuidaima.regularexpression;  
  2.   
  3. import java.util.regex.Matcher;  
  4. import java.util.regex.Pattern;  
  5.   
  6. public class UserReg {  
  7.     /** 
  8.      * 验证用户名,支持中英文(包括全角字符)、数字、下划线和减号 (全角及汉字算两位),长度为4-20位,中文按二位计数 
  9.      *  
  10.      * @param userName 
  11.      * @return 
  12.      */  
  13.     public static boolean validateUserName(String userName) {  
  14.         String validateStr = "^[\\w\\--_[0-9]\u4e00-\u9fa5\uFF21-\uFF3A\uFF41-\uFF5A]+$";  
  15.         boolean rs = false;  
  16.         rs = matcher(validateStr, userName);  
  17.         if (rs) {  
  18.             int strLenth = getStrLength(userName);  
  19.             if (strLenth < 4 || strLenth > 20) {  
  20.                 rs = false;  
  21.             }  
  22.         }  
  23.         return rs;  
  24.     }  
  25.   
  26.     /** 
  27.      * 获取字符串的长度,对双字符(包括汉字)按两位计数 
  28.      *  
  29.      * @param value 
  30.      * @return 
  31.      */  
  32.     public static int getStrLength(String value) {  
  33.         int valueLength = 0;  
  34.         String chinese = "[\u0391-\uFFE5]";  
  35.         for (int i = 0; i < value.length(); i++) {  
  36.             String temp = value.substring(i, i + 1);  
  37.             if (temp.matches(chinese)) {  
  38.                 valueLength += 2;  
  39.             } else {  
  40.                 valueLength += 1;  
  41.             }  
  42.         }  
  43.         return valueLength;  
  44.     }  
  45.   
  46.     private static boolean matcher(String reg, String string) {  
  47.         boolean tem = false;  
  48.         Pattern pattern = Pattern.compile(reg);  
  49.         Matcher matcher = pattern.matcher(string);  
  50.         tem = matcher.matches();  
  51.         return tem;  
  52.     }  
  53.   
  54.     public static void main(String[] args) {  
  55.         String str = "0-_f9zd中22最代码zuidaima.com";  
  56.         String st = "A-dq_!!!!去符号标号!ノチセたのひちぬ!当然。!!..**半角最代码zuidaima.com";  
  57.   
  58.         System.out.println(validateUserName(str));  
  59.         System.out.println(st.replaceAll("[\\pP&&[^-_]]"""));  
  60.         System.out.println(st.replaceAll("[\\w\\-一-龥A-Za-z]"""));  
  61.     }  
  62. }  
  63.   
  64.        
0 0
原创粉丝点击