I’m trying to build a Java regex that supports date times (where the time component is military time):
MM/dd/YYYY HH:mm:ss
@Test
public void testRegexPattern() {
String regex = "([0-9]{2})/([0-9]{2})/([0-9]{4}\\s^([01]\\d|2[0-3]):?([0-5]\\d):?([0-5]\\d)$)";
String supposedDateTime = "12/31/1969 19:00:00";
Assert.assertTrue(supposedDateTime.matches(regex));
}
This test is failing because the supposedDateTime doesn’t match the regex. Can any regex maestros out there spot why? Thanks in advance.
Why are you having
caret(^)in the middle after\\s? Remove it. That is what creating the problem. Also, withString#matchesmethod, you don’t even need to useanchors.So, you can use this regex:
Having talked about the actual issue in regex, you should really not test dates with regex. Rather use
SimpleDateFormatwith appropriate pattern toparsethe date string.