加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 23:09:25 所属栏目:百科 来源:网络整理
导读:用户名可能包含中文,中文按2位算 代码下载地址:http://www.zuidaima.com/share/1550463222516736.htm 转载请注明出处:验证用户名长度的正则表达式 运行此代码截图如下: 满足此表达式: 不满足此表达式: package com.zuidaima.regularexpression;import java.

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

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

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

运行此代码截图如下:

满足此表达式:

不满足此表达式:

package com.zuidaima.regularexpression;

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

public class UserReg {
	/**
	 * 验证用户名,支持中英文(包括全角字符)、数字、下划线和减号 (全角及汉字算两位),长度为4-20位,中文按二位计数
	 * 
	 * @param userName
	 * @return
	 */
	public static boolean validateUserName(String userName) {
		String validateStr = "^[w--_[0-9]u4e00-u9fa5uFF21-uFF3AuFF41-uFF5A]+$";
		boolean rs = false;
		rs = matcher(validateStr,userName);
		if (rs) {
			int strLenth = getStrLength(userName);
			if (strLenth < 4 || strLenth > 20) {
				rs = false;
			}
		}
		return rs;
	}

	/**
	 * 获取字符串的长度,对双字符(包括汉字)按两位计数
	 * 
	 * @param value
	 * @return
	 */
	public static int getStrLength(String value) {
		int valueLength = 0;
		String chinese = "[u0391-uFFE5]";
		for (int i = 0; i < value.length(); i++) {
			String temp = value.substring(i,i + 1);
			if (temp.matches(chinese)) {
				valueLength += 2;
			} else {
				valueLength += 1;
			}
		}
		return valueLength;
	}

	private static boolean matcher(String reg,String string) {
		boolean tem = false;
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(string);
		tem = matcher.matches();
		return tem;
	}

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

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

	    			

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读