下面的示例演示如何使用String类的matchs方法检查日期是否为正确的格式。
public class Main { public static void main(String[] argv) { boolean isDate = false; String date1 = "8-05-1988"; String date2 = "08/04/1987"; String datePattern = "\\d{1,2}-\\d{1,2}-\\d{4}"; isDate = date1.matches(datePattern); System.out.println("Date :"+ date1+": matches with the this date Pattern:"+datePattern+"Ans:"+isDate); isDate = date2.matches(datePattern); System.out.println("Date :"+ date2+": matches with the this date Pattern:"+datePattern+"Ans:"+isDate); } }
上面的代码示例将产生以下结果。
Date :8-05-1988: matches with the this date Pattern: \d{1,2}-\d{1,2}-\d{4}Ans:true Date :08/04/1987: matches with the this date Pattern: \d{1,2}-\d{1,2}-\d{4}Ans:false
以下是检查日期是否为正确格式的示例。
import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String args[]) { List dates = new ArrayList(); dates.add("25/12/1990"); dates.add("25/12/1990"); dates.add("12/12/90"); dates.add("05/02/1990"); String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$"; Pattern pattern = Pattern.compile(regex); for(Object date : dates) { Matcher matcher = pattern.matcher((CharSequence) date); System.out.println(date +" : "+ matcher.matches()); } } }
上面的代码示例将产生以下结果。
25/12/1990 : false 25/12/1990 : false 12/12/90 : false 05/02/1990 : true