年月日一般是由 年,月,日或者其他的连接符号("/" ,".","-")组成。
第一种:
2008-12-12
"\\d{4}-([1-9]|(1[0-2]))-([1-9]|([1|2]\\d)|(3(1|0)))"
\\d{4}-([1-9]|(1[0-2]))-([1-9]|([12]\\d)|(3(1|0)))
public
class
RegexDemo5 {
public
static
void
main(String[] args) {
String str=
"2008-12-12"
;
String pat=
"\\d{4}-([1-9]|(1[0-2]))-([1-9]|([1|2]\\d)|(3(1|0)))"
;
boolean
temp=str.matches(pat);
System.
out
.println(temp);
}
}
public
class
RegexDemo5 {
public
static
void
main(String[] args) {
String str=
"2008-11-12"
;
String pat=
"\\d{4}-([1-9]|(1[0-2]))-([1-9]|([12]\\d)|(3(1|0)))"
;
boolean
temp=str.matches(pat);
System.
out
.println(temp);
}
}
结果:
true
但是这种不能验证如:2008.12.11这种
2.
\\d{4}[-/.]([1-9]|(1[0-2]))[-/.]([1-9]|([12]\\d)|(3[01]))
public
class
RegexDemo6 {
public
static
void
main(String[] args) {
String str=
"2008.12.12"
;
String str1=
"2008/12/12"
;
String str2=
"2008-12-12"
;
String pat=
"\\d{4}[-/.]([1-9]|(1[0-2]))[-/.]([1-9]|([12]\\d)|(3[01]))"
;
boolean
temp=str.matches(pat);
boolean
temp1=str1.matches(pat);
boolean
temp2=str2.matches(pat);
System.
out
.println(
"temp--->"
+temp+
"-----temp1--->"
+temp1+
"----temp2--->"
+temp2);
}
}
结果:
temp--->true-----temp1--->true----temp2--->true
如:
public
class
RegexDemo6 {
public
static
void
main(String[] args) {
String str=
"2008.12/12" ;
String str1= "2008/12-12" ;
String str2= "2008.12-12" ;
String str=
"2008.01/12"
;//这种也不行
String pat=
"\\d{4}[-/.]([1-9]|(1[0-2]))[-/.]([1-9]|([12]\\d)|(3[01]))"
;
boolean
temp=str.matches(pat);
boolean
temp1=str1.matches(pat);
boolean
temp2=str2.matches(pat);
System.
out
.println(
"temp--->"
+temp+
"-----temp1--->"
+temp1+
"----temp2--->"
+temp2);
}
}
结果:
temp--->true-----temp1--->true----temp2--->true
上面列举了许多bug,希望在输入的时候进行要求,也可以对正则表达式进行更加严密的书写
比如:
\\d{4}[-/.]((0?\\d)|(1[0-2]))[-/.]((0?\\d)|([12]\\d)|(3[01]))
这个就能解决输入月份为:01这样的bug
还有就是闰年与平年的区别。。。。这些都要考虑。。。。。我在这里就不写了