代码:
package com.day02;
/*
* 正则表达式匹配时间日期
*
*/
public class day08 {
public static void main(String[] args) {
// 1.匹配日期:yyyy-MM-dd
String regex1 = "\\d{4}-\\d{2}-\\d{2}";
String regex2 = "\\d{4}/\\d{2}/\\d{2}";
String par1 = "2023-10-11";
boolean isMatch1 = par1.matches(regex1);
System.out.println("1.匹配日期yyyy-MM-dd:"+isMatch1); // true
String par2 = "2023/03/30";
boolean isMatch2 = par2.matches(regex2);
System.out.println("1.匹配日期yyyy/MM/dd:"+isMatch2); // true
// 2.匹配时间:HH:mm:ss
String regex3 = "\\d{2}:\\d{2}:\\d{2}";
String par3 = "23:45:30";
boolean isMatch3 = par3.matches(regex3);
System.out.println("2.匹配时间HH:mm:ss:"+isMatch3); // true
// 3.匹配年份:yyyy
String regex4 = "\\d{4}";
String par4 = "2023";
boolean isMatch4 = par4.matches(regex4);
System.out.println("3.匹配年份yyyy:"+isMatch4); // true
// 4.匹配日期时间:yyyy-MM-dd HH:mm:ss
String regex5 = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}";
String par5 = "2023-09-01 14:24:49";
boolean isMatch5 = par5.matches(regex5);
System.out.println("4.匹配日期时间yyyy-MM-dd HH:mm:ss:"+isMatch5); // true
// 5.其它时间格式:MM/dd/yyyy
String regex6 = "\\d{2}/\\d{2}/\\d{4}";
String par6 = "09/10/2023";
boolean isMatch6 = par6.matches(regex6);
System.out.println("5.其它时间格式MM/dd/yyyy:"+isMatch6); // true
}
}
测试输出:
1.匹配日期yyyy-MM-dd:true
1.匹配日期yyyy/MM/dd:true
2.匹配时间HH:mm:ss:true
3.匹配年份yyyy:true
4.匹配日期时间yyyy-MM-dd HH:mm:ss:true
5.其它时间格式MM/dd/yyyy:true