【java】正则判断是否日期(年月日)字符串
/** * 日期分隔符,处理特殊字符 * * @param splitter * @return */ private static String dealWithSplitter(char splitter) { String strSplitter = String.valueOf(splitter); String[] str = {".", "+", "*", "|", "?"}; if (Arrays.asList(str).contains(strSplitter)) { strSplitter = "[" + strSplitter + "]"; } else if ("^".equals(strSplitter)) { strSplitter = "\\^"; } else if ("(".equals(strSplitter)) { strSplitter = "\\("; } else if (")".equals(strSplitter)) { strSplitter = "\\)"; } else if ("{".equals(strSplitter)) { strSplitter = "\\{"; } else if ("}".equals(strSplitter)) { strSplitter = "\\}"; } else if ("[".equals(strSplitter)) { strSplitter = "\\["; } else if ("]".equals(strSplitter)) { strSplitter = "\\]"; } return strSplitter; } /*** * 判断字符串是否是yyyyMMdd、yyyyMdd、yyyyMMd、yyyyMd格式,分隔符为splitter参数 * 例如:yyyy-MM-dd、yyyy.MM.dd * * @param mes * @param splitter * @return */ public static boolean isRqFormat(String mes, char splitter){ if (null == mes || 0 == mes.length()) { return false; } String strSplitter = dealWithSplitter(splitter); // 1000年——2020 // String format = "(1[0-9]{3}|20([0-1]{1}[0-9]{1}|20))" + strSplitter + "([1-9]|0[1-9]|1[012])" + strSplitter + "([1-9]|0[1-9]|[12][0-9]|3[01])"; // 0000年——9999年 String format = "([0-9]{4})" + strSplitter + "([1-9]|0[1-9]|1[012])" + strSplitter + "([1-9]|0[1-9]|[12][0-9]|3[01])"; Pattern pattern = Pattern.compile(format); Matcher matcher = pattern.matcher(mes); if (!matcher.matches()) { return false; } pattern = Pattern.compile("(\\d{4})" + strSplitter + "(\\d{1,2})" + strSplitter + "(\\d{1,2})"); matcher = pattern.matcher(mes); if (!matcher.matches()) { return false; } int y = Integer.valueOf(matcher.group(1)); int m = Integer.valueOf(matcher.group(2)); int d = Integer.valueOf(matcher.group(3)); if (d > 28) { Calendar c = Calendar.getInstance(); c.set(y, m-1, 1); int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH); return lastDay >= d; } return true; } /*** * 判断字符串是否是yyyyMMdd、yyyyMdd、yyyyMMd、yyyyMd格式 * * @param mes * @return */ public static boolean isRqFormat(String mes){ if (null == mes || 0 == mes.length()) { return false; } // 1000年——2020 // String format = "(1[0-9]{3}|20([0-1]{1}[0-9]{1}|20))([1-9]|0[1-9]|1[012])([1-9]|0[1-9]|[12][0-9]|3[01])"; // 0000年——9999年 String format = "([0-9]{4})([1-9]|0[1-9]|1[012])([1-9]|0[1-9]|[12][0-9]|3[01])"; Pattern pattern = Pattern.compile(format); Matcher matcher = pattern.matcher(mes); if (!matcher.matches()) { return false; } pattern = Pattern.compile("(\\d{4})(\\d{1,2})(\\d{1,2})"); matcher = pattern.matcher(mes); if (!matcher.matches()) { return false; } int y = Integer.valueOf(matcher.group(1)); int m = Integer.valueOf(matcher.group(2)); int d = Integer.valueOf(matcher.group(3)); if (d > 28) { Calendar c = Calendar.getInstance(); c.set(y, m-1, 1); int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH); return lastDay >= d; } return true; }