- 是否是闰年
public static void main(String[] args) {
//用正则时,如果是闰年2有有29天,否则是2月有28天
//29// (闰年-02-29)|(\\d+-02-28)
String day29 = "(^[48][0]*$)"
+ "|(^\\d*([02468][48]|[13579][26]|[2468]0)$)"
+ "|(^\\d*([24680][480]|[13579][26])00$)";
//验证 一千万年
for (int i = 1; i < 10000000; i += 1) {
//不能被400整除,能被100整除的都是平年
if (i % 100 == 0 && i % 400 != 0) {
//如果得出是闰年 则出错
if (String.valueOf(i).matches(day29)) {
System.out.println(i);
break;
}
} else {
if (i % 4 == 0) {
//如果得出不是闰年 则出错
if (!String.valueOf(i).matches(day29)) {
System.out.println(i);
break;
}
}
}
}
}
- 普通年份的验证
31天的有1,3,5,7,8,10,12月,正则式为: ^(((([0]?[1-9])|([12]\\d)|(3[01]))/(([0]?1)|([0]?3)|([0]?5)|([0]?7)|([0]?8)|(10)|(12))))/\\d+$
30天的有4,6,9,11月,正则式为: ^(((([0]?[1-9])|([12]\\d)|(30))/(([0]?4)|([0]?6)|([0]?9)|(11)))) /\\d+$
28天的有2月,正则式为: ^(((([0]?[1-9])|(1\\d)|(2[0-8]))/[0]?2))/\\d+$
合起来1-12月为: ^(((([0]?[1-9])|([12]\\d)|(3[01]))/(([0]?1)|([0]?3)|([0]?5)|([0]?7)|([0]?8)|(10)|(12)))|((([0]?[1-9])|([12]\\d)|(30))/(([0]?4)|([0]?6)|([0]?9)|(11)))|((([0]?[1-9])|(1\\d)|(2[0-8]))/[0]?2))/\\d+$
- 闰年必定有2月29,设定日期格式为 dd/MM/yyyy
又因为正则只有"|",或运算: 从左到右,只要遇到有条件成立,则为true
验证日期时,如果是2月29则必定为闰年,否则则是普通年份
闰年并且为2月29日的正则式为(^29/[0]?2/[48][0]*$)|(^29/[0]?2/\\d*([02468][48]|[13579][26]|[2468]0)$)|(^29/[0]?2/\\d*([24680][480]|[13579][26])00$)
综合起来,验证表达式为:(^29/[0]?2/[48][0]*$)|(^29/[0]?2/\\d*([02468][48]|[13579][26]|[2468]0)$)|(^29/[0]?2/\\d*([24680][480]|[13579][26])00$)
| (^(((([0]?[1-9])|([12]\\d)|(3[01]))/(([0]?1)|([0]?3)|([0]?5)|([0]?7)|([0]?8)|(10)|(12)))|((([0]?[1-9])|([12]\\d)|(30))/(([0]?4)|([0]?6)|([0]?9)|(11)))|((([0]?[1-9])|(1\\d)|(2[0-8]))/[0]?2))/\\d+$)