package com.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-\u9fa5\uFF21-\uFF3A\uFF41-\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"; String st = "A-dq_!!!!去符号标号!ノチセたのひちぬ!当然。!!..**半角"; System.out.println(validateUserName(str)); System.out.println(st.replaceAll("[\\pP&&[^-_]]", "")); System.out.println(st.replaceAll("[\\w\\-一-龥A-Za-z]", "")); } }
最近下载更多
张瀺 LV1
2021年10月10日
HighMlinxi LV1
2021年4月28日
dfsdfsd23423 LV1
2020年10月1日
天翊12345678 LV1
2020年3月29日
公子小徐 LV1
2019年1月23日
shanpengnian LV13
2018年6月22日
故事_sun LV26
2018年5月16日
饭饭君 LV1
2018年5月8日
bianyuanze LV9
2018年4月21日
aihui523 LV34
2017年8月21日
最近浏览更多
奔跑的酱油 LV1
2月29日
kang1919
2023年2月24日
暂无贡献等级
xy2免费空间资源论坛 LV2
2022年9月6日
Huller
2022年7月16日
暂无贡献等级
张瀺 LV1
2021年10月10日
wujixiaofeng
2021年7月16日
暂无贡献等级
HighMlinxi LV1
2021年4月28日
sbsbsbsbsb LV10
2021年4月12日
dfsdfsd23423 LV1
2020年10月1日
huaidanzf LV1
2020年9月15日