hrishikeshp19
hrishikeshp19

Reputation: 9028

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?

Upvotes: 2

Views: 66

Answers (1)

Roddy of the Frozen Peas
Roddy of the Frozen Peas

Reputation: 15184

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.

Upvotes: 3

Related Questions