java正则表达式检查日期格式

时间:2014-11-18 22:36:27

标签: java regex

private static String REGEX_ANY_MONTH = "January|Jan|February|Feb|March|Mar|April|Apr|May|June|Jun|"
        + "July|Jul|August|Aug|September|Sep|October|Oct|November|Nov|December|Dec";
private static String REGEX_ANY_YEAR = "[0-9]{4}";
private static String REGEX_ANY_DATE = "[0-9]{1,2}";

private String getFormat(String date) {
    if (date.matches(REGEX_ANY_MONTH + " " + REGEX_ANY_DATE + "," + " " + REGEX_ANY_YEAR)) {
        return "{MONTH} {DAY}, {YEAR}";
    } else if (date.matches(REGEX_ANY_MONTH + " " + REGEX_ANY_YEAR)){
        return "{MONTH} {YEAR}";
    }
    return null;
}


@Test
public void testGetFormatDateString() throws Exception{
    String format = null;
    String test = null;
    test = "March 2012";
    format = Whitebox.<String> invokeMethod(obj, "getFormat", test);
    Assert.assertEquals("{MONTH} {YEAR}", format);

    test = "March 10, 2012";
    format = Whitebox.<String> invokeMethod(obj, "getFormat", test);
    Assert.assertEquals("{MONTH} {DATE}, {YEAR}", format);

}

这两个断言对我来说都是失败的。我错过了什么?

1 个答案:

答案 0 :(得分:3)

您需要将月份名称的管道列表包装在括号中,以便匹配。

private static String REGEX_ANY_MONTH = "(January|Jan|February|Feb|March|Mar|April|Apr|May|June|Jun|"
    + "July|Jul|August|Aug|September|Sep|October|Oct|November|Nov|December|Dec)";

否则'或'条件将超过月份。