正则表达式练习
判断身份证:要么是15位,要么是18位,最后一位可以为字母,并写程序提出其中的年月日。
public static void main(String[] args) { testID_Card(); } public static void testID_Card() { // 测试是否为合法的身份证号码 String[] strs = { "130681198712092019", "13068119871209201x", "13068119871209201", "123456789012345", "12345678901234x", "1234567890123" }; // 准备正则表达式(身份证有15位和18位两种,身份证的最后一位可能是字母) String regex = "(\d{14}\w)|\d{17}\w"; // 准备开始匹配,判断所有的输入是否是正确的 Pattern regular = Pattern.compile(regex); // 创建匹配的规则Patter StringBuilder sb = new StringBuilder(); // 遍历所有要匹配的字符串 for (int i = 0; i < strs.length; i++) { Matcher matcher = regular.matcher(strs[i]);// 创建一个Matcher sb.append("身份证: "); sb.append(strs[i]); sb.append(" 匹配:"); sb.append(matcher.matches()); System.out.println(sb.toString()); sb.delete(0, sb.length());// 清空StringBuilder的方法 } GetBirthDay(strs); } private static void GetBirthDay(String[] strs) { System.out.println("准备开始获取出生日期"); // 准备验证规则 Pattern BirthDayRegular = Pattern.compile("(\d{6})(\d{8})(.*)"); // .*连在一起就意味着任意数量的不包含换行的字符 Pattern YearMonthDayRegular = Pattern .compile("(\d{4})(\d{2})(\d{2})"); for (int i = 0; i < strs.length; i++) { Matcher matcher = BirthDayRegular.matcher(strs[i]); if (matcher.matches()) { Matcher matcher2 = YearMonthDayRegular .matcher(matcher.group(2)); if (matcher2.matches()) { System.out.println(strs[i]+" 中的出生年月分解为: "+"年" + matcher2.group(1) + " 月:" + matcher2.group(2) + " 日:" + matcher2.group(3)); } } } }