简体   繁体   English

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

[英]java regular expression check date format

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);

}

Both of the asserts are failing for me. 这两个断言对我来说都是失败的。 What am I missing? 我想念什么?

You need to wrap your piped list of month names in parentheses in order for it to match. 您需要将管道的月份名称列表包装在括号中才能匹配。

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)";

Otherwise the 'or' condition will be or-ing more than just the month. 否则,“或”条件将不仅仅是一个月。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM