正则校验
正则校验和内容格式替换
一、正则校验
1.手机号码
public static boolean isMobileNO(String mobiles) {
/*
移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188、178
联通:130、131、132、152、155、156、185、186、176
电信:133、153、180、189、(1349卫通)、177
结论:第一位必定为1,第二位必定为3/5/8/7,其他位置为 0-9
*/
String telRegex = "[1][34578]\\d{9}";//"[1]"代表第1位为数字1,"[3458]"代表第二位可以为3、4、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。
if (StringUtils.isEmpty(mobiles)) return false;
else return mobiles.matches(telRegex);
}
2.QQ号
public static boolean isQq(String qq) {
// 5至11位
String str = "^[1-9][0-9]{4,10}$";
if (StringUtils.isEmpty(qq)) return false;
return qq.matches(str);
}
3.微信号
public static boolean isWeixin(String weixin) {
// 微信号正则,6至20位,以字母开头,字母,数字,减号,下划线
String str = "^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$";
if (StringUtils.isEmpty(weixin)) return false;
return weixin.matches(str);
}
4.车牌号
public static boolean isCar(String carNum) {
String str = "^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$";
if (StringUtils.isEmpty(carNum)) return false;
return carNum.matches(str);
}
5.身份证号码
public static boolean isIdCardNo(String idNum) {
if (StringUtils.isEmpty(idNum)) return false;
// 定义判别用户身份证号的正则表达式(15位/18位,最后一位可以为字母)
Pattern idNumPattern = Pattern.compile("(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])");
// 通过Pattern获得Matcher
Matcher idNumMatcher = idNumPattern.matcher(idNum);
if (!idNumMatcher.matches()) {
return false;
}
return true;
}
6.邮箱
public static boolean isEmail(String email) {
String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
if (StringUtils.isEmpty(email)) return false;
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(email);
return m.matches();
}
7.判断中文符号
Character.UnicodeBlock 取值
UnicodeBlock | 含义 |
---|---|
CJK_UNIFIED_IDEOGRAPHS | CJK统一表意符号 Unicode字符块的常数 |
CJK_COMPATIBILITY_IDEOGRAPHS | CJK兼容性表意符号 Unicode字符块的常量 |
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A | CJK统一表意扩展A Unicode字符块的常数 |
GENERAL_PUNCTUATION | 常规为“一般标点符号” Unicode字符块 |
CJK_SYMBOLS_AND_PUNCTUATION | 常量为“CJK符号和标点符号” Unicode字符块 |
HALFWIDTH_AND_FULLWIDTH_FORMS | Unicode字符块的“半宽和全宽”的常量 |
/**
* 校验中文汉字
*/
private static final boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
// 获取此字符的UniCodeBlock
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
return true;
}
return false;
}
/**
* 校验一个字符是否是汉字
*
* @param c 校验的字符
* @return true代表是汉字
*/
public static boolean isChineseChar(char c) {
try {
return String.valueOf(c).getBytes("UTF-8").length > 1;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return false;
}
}
/**
* 校验是否含有非法字符
* `~!#%^&*=+\\|{};:'\",<>/?○●★☆☉♀♂※¤╬の〆
*
* @param content 符串内容
* @return 't' 代表不包含非法字符,otherwise代表包含非法字符。
*/
public static char validateLegalString(String content) {
String illegal = "`~!#%^&*=+\\|{};:'\",<>/?○●★☆☉♀♂※¤╬の〆";
char isLegalChar = 't';
L1: for (int i = 0; i < content.length(); i++) {
for (int j = 0; j < illegal.length(); j++) {
if (content.charAt(i) == illegal.charAt(j)) {
isLegalChar = content.charAt(i);
break L1;
}
}
}
return isLegalChar;
}
/**
* 验证是否是汉字或者0-9、a-z、A-Z
*
* @param c 验证的char
* @return true 代表符合条件
*/
public static boolean isRightChar(char c) {
return isChinese(c) || isWord(c);
}
/**
* 校验某个字符是否是a-z、A-Z、_、0-9
*
* @param c 校验的字符
* @return true代表符合条件
*/
public static boolean isWord(char c) {
String regEx = "[\\w]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher("" + c);
return m.matches();
}
/*
* 校验String是否全是中文
*
* @param name 校验的字符串
* @return true 代表全是汉字
*/
public static boolean checkNameChese(String name) {
boolean res = true;
char[] cTemp = name.toCharArray();
for (int i = 0; i < name.length(); i++) {
if (!isChinese(cTemp[i])) {
res = false;
break;
}
}
return res;
}
二、内容格式替换
1.手机号加密显示
正则表达式中使用 $1 和 $2 表示 第一个 ( ) 、第二个 ( ) 中的内容
Demo:$1****$2 将中间部分替换为 *
public static String resetPhone(String phone) {
if (StringUtils.isEmpty(phone)) {
return "";
} else {
// 将中间4位 替换为 *
String phoneNum = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
return phoneNum;
}
}
2.验证日期字符串是否符合 YYYY-MM-DD 格式
private static boolean toDateFormat(String str) {
String regxStr = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$";
Pattern pat = Pattern.compile(regxStr);
Matcher m = pat.matcher(str);
if (m.matches()) return true;
return false;
}
3.数字转格式
将 1435 -> 1.4k | 14350 -> 1.4w | 25 -> 325
(保留的小数位数)newScale - 要退回的 BigDecimal值的比例
(入模式)roundingMode - 要应用的舍入模式
- BigDecimal.ROUND_HALF_UP 四舍五入
public static String formatNum(String num) {
String no = "";
if (num != null) {
if (Integer.parseInt(num) >= 10000) {
double num1 = (double) Double.parseDouble(num) / 10000;
BigDecimal b = new BigDecimal(num1);
double f1 = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
no = f1 + "w";
} else if (Integer.parseInt(num) >= 1000 && Integer.parseInt(num) < 10000) {
double num2 = (double) Double.parseDouble(num) / 1000;
BigDecimal b = new BigDecimal(num2);
double f2 = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
no = f2 + "k";
} else {
no = num;
}
}
return no;
}
4.身份证的有效验证
public static boolean IDCardValidate(String IDStr) throws ParseException {
String errorInfo = "";// 记录错误信息
String[] ValCodeArr = {"1", "0", "x", "9", "8", "7", "6", "5", "4",
"3", "2"};
String[] Wi = {"7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7",
"9", "10", "5", "8", "4", "2"};
String Ai = "";
// 身份证号码的长度 15位或18位
if (IDStr.length() != 15 && IDStr.length() != 18) {
errorInfo = "身份证号码长度应该为15位或18位。";
return false;
}
// 身份证号码除最后一位都为数字
if (IDStr.length() == 18) {
Ai = IDStr.substring(0, 17);
} else if (IDStr.length() == 15) {
Ai = IDStr.substring(0, 6) + "19" + IDStr.substring(6, 15);
}
if (isNumeric(Ai) == false) {
errorInfo = "身份证15位号码都应为数字 ; 18位号码除最后一位外,都应为数字。";
return false;
}
// 生年月是否有效
String strYear = Ai.substring(6, 10);// 年份
String strMonth = Ai.substring(10, 12);// 月份
String strDay = Ai.substring(12, 14);// 月份
if (isDataFormat(strYear + "-" + strMonth + "-" + strDay) == false) {
errorInfo = "身份证生日无效。";
return false;
}
GregorianCalendar gc = new GregorianCalendar();
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
try {
if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150
|| (gc.getTime().getTime() - s.parse(
strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) {
errorInfo = "身份证生日不在有效范围。";
return false;
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) {
errorInfo = "身份证月份无效";
return false;
}
if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {
errorInfo = "身份证日期无效";
return false;
}
// 地区码时候有效
Hashtable h = GetAreaCode();
if (h.get(Ai.substring(0, 2)) == null) {
errorInfo = "身份证地区编码错误。";
return false;
}
// 判断最后一位的值
int TotalmulAiWi = 0;
for (int i = 0; i < 17; i++) {
TotalmulAiWi = TotalmulAiWi
+ Integer.parseInt(String.valueOf(Ai.charAt(i)))
* Integer.parseInt(Wi[i]);
}
int modValue = TotalmulAiWi % 11;
String strVerifyCode = ValCodeArr[modValue];
Ai = Ai + strVerifyCode;
if (IDStr.length() == 18) {
if (Ai.equals(IDStr) == false) {
errorInfo = "身份证无效,不是合法的身份证号码";
return false;
}
} else {
return true;
}
return true;
}
/**
* 是否全是数字
*/
public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
if (StringUtils.isEmpty(str)) return false;
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}