常见的重要号码校验规则,邮箱的格式验证
手机号码的校验规则邮箱格式的验证身份证号格式的验证手机号码的校验规则
方法:手机号码校验
。
// 引入包文件import mons.lang3.StringUtils;import java.util.Scanner;import java.util.regex.Matcher;import java.util.regex.Pattern;;
// 第一种方法public static int checkPhoneNo(String phone) throws BusinessException {int status = 0;String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";if (StringUtils.isEmpty(phone)) {status = 1;throw new BusinessException(1,"手机号码为空");} else {if (phone.length() != 11) {System.out.println("手机号码必须为11位数字");status = 2;throw new BusinessException(1,"手机号应为11位数");} else {Pattern p = pile(regex);Matcher m = p.matcher(phone);boolean isMatch = m.matches();if (isMatch) {System.out.println("恭喜您,您的手机号码" + phone + "是正确格式!!");} else {System.out.println("对不起,您的手机号码" + phone + "是错误格式!!");status = 3;throw new BusinessException(1,"手机号码验证失败,请填写正确的手机号");}}}return status;}//第二种方法public static boolean validPhoneNo(String phoneNo) {if ((phoneNo!= null) && (!phoneNo.isEmpty())) {return Pattern.matches("^1[3-9]\\d{9}$", phoneNo);}return false;}private static class BusinessException extends Throwable {public BusinessException(int status, String message) {}}
邮箱格式的验证
邮箱格式的验证邮箱验证
// 两种方法String regex = ^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$;String pattern="^[A-Za-z0-9\u4e00-\u9fa5]+(\\.[A-Za-z0-9\u4e00-\u9fa5]+)*@[A-Za-z0-9\u4e00-\u9fa5]+(\\.[A-Za-z0-9\u4e00-\u9fa5]+)*(\\.[A-Za-z\u4e00-\u9fa5]{2,})$";
// 验证邮箱的正则表达式public static boolean isValidEmail(String email) {if ((email != null) && (!email.isEmpty())) {return Pattern.matches("^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$", email);}return false;}//使用延迟初始化优化Pattern对象private static Pattern pattern = null;public static boolean validateEmail(String email) {if(pattern == null) {pattern = pile("^[A-Za-z0-9\u4e00-\u9fa5]+(\\.[A-Za-z0-9\u4e00-\u9fa5]+)*@[A-Za-z0-9\u4e00-\u9fa5]+(\\.[A-Za-z0-9\u4e00-\u9fa5]+)*(\\.[A-Za-z\u4e00-\u9fa5]{2,})$");}Matcher matcher = pattern.matcher(email);return matcher.matches();}
身份证号格式的验证
身份证号格式的验证身份证号验证
//身份证号码验证//第一代身份证15位 String regexIDCard15 = "^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$";//第二代身份证18位 String regexIDCard18 = "^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";
import java.util.regex.Matcher;import java.util.regex.Pattern;public class IDCard {private static final String regexIDCard15 = "^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$";private static final String regexIDCard18 = "^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";public static void main(String[] args) {regexIDCard("41032519980925243X");}public static void regexIDCard(String cardNo) {String id_valid="("+regexIDCard15+")"+"|"+"("+regexIDCard18+")";Pattern pattern1 =pile(id_valid);Matcher matcher =pattern1.matcher(cardNo);System.out.println(matcher.matches());}}