常用正则
记录几个正则,搜集并稍微整理了下,基本满足需求。
校验还是稍微有点严谨的,
手机号是对号段进行校验,支持166和167号段。
银行卡号由于手里的卡bin不全,所以暂时无法进行卡bin的校验,只能粗略的校验位数,通常是16或19位数字,但是实际发现有其他位数的银行卡号,所以这里判断16~19位的都可以。
邮箱就是通常的都可以。
身份证的校验了格式和最后一位校验码,所以乱输的肯定不可以。
public class CommonUtils {
/*
* 正则用法如下
* Matcher cardMatcher = CommonUtils.bankCardPattern.matcher(cardNo);
* cardMatcher.find(); // 返回true表示校验通过
*/
// 手机号
private static final String phoneRegExp = "^1([38][0-9]|4[1,4-9]|5[0-3,5-9]|6[6-7]|7[0-8]|9[189])\\d{8}$";
public static Pattern phoneRegPattern = Pattern.compile(phoneRegExp);
// 银行卡号
private static final String bankCardRegExp = "^([1-9]{1})(\\d{15,18})$";
public static Pattern bankCardPattern = Pattern.compile(bankCardRegExp);
// 邮箱
private static final String mailRegExp = "^[a-z0-9]+([._\\\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+\\.){1,63}[a-z0-9]+$";
public static Pattern mailRegPattern = Pattern.compile(mailRegExp);
// 身份证号格式
private static Pattern idNumberRegPattern = Pattern.compile("^(?i)\\d{17}(\\d|x)$");
// {11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"}
private static Set<String> citySet = new HashSet<>(Arrays.asList("11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "71", "81", "82", "91"));
/**
* 校验身份证
* @param idNumber 身份证号
* @return 通过返回true,否则返回false
*/
public static boolean validIdNumber(String idNumber) {
boolean result = false;
Date parse;
Date now = new Date();
int sum = 0;
char residue;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
int[] arrInt = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
char[] arrCh = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
try {
String birthday = idNumber.substring(6, 10) + idNumber.substring(10, 12) + idNumber.substring(12, 14);
parse = sdf.parse(birthday);
if (idNumberRegPattern.matcher(idNumber).find()) {
if (citySet.contains(idNumber.substring(0, 2))) {
if (now.compareTo(parse) > 0) {
for (int i = 0; i < 17; i++) {
sum += Integer.parseInt(String.valueOf(idNumber.charAt(i))) * arrInt[i];
}
residue = arrCh[sum % 11];
if (residue == idNumber.charAt(17)) {
result = true;
}
}
}
}
} catch (Exception e) {
// 吃掉异常
}
return result;
}
}
这里是把做成工具类方便统一使用。参考了比较多的文章,忘记保存了,所以就不贴引用网址了。内容基本来自网络,我只是最后整理下,并且测试使用没问题。