老师昨天布置的题目,到现在不知道如何解决,题目如下:正则表达式已经获得广泛的应用和支持.写一个程序接收控制台输入的字符串,并用正则表达式来判断是否符合"YYYY-YY-YY"这种日期格式,并在控制台输出结果.多谢各位指教!~~不胜感激!~~

解决方案 »

  1.   

    public class test { /**
     * @param args
     */
    public static void main(String[] args) {
    String tmp = "2008-12-31";
    boolean boo = tmp
    .matches("[1-9][0-9]{3}\\-(0[0-9]|1[0-2])\\-(0[0-9]|1[0-9]|2[0-9]|3[0-1])");
    System.out.println("boo   =" + boo); }}
      

  2.   

    yyyy-MM-dd这种格式是可以判断
    但是闰年2月天数就不能判断,不推荐用正则表达式用这个最简单:        public static boolean isDate(String strDate, String dateFormat) {
                SimpleDateFormat df = new SimpleDateFormat(dateFormat);
                try {
                    Date tmpDate = df.parse(strDate);
                    String strTempDate = df.format(tmpDate);
                    if (!strTempDate.equals(strDate)) {
                        return false;
                    }
                }
                catch (Exception e) {
                    return false;
                }
                return true;
            }
      

  3.   

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;public class test { /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
    String str = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter your value:");
    str = br.readLine();
    boolean boo = str
    .matches("[1-9][0-9]{3}\\-(0[0-9]|1[0-2])\\-(0[0-9]|1[0-9]|2[0-9]|3[0-1])");
    System.out.println("boo   =" + boo); }}