Regex is overkill
If you have a limited number of non-ambiguous formats in play, simply attempt parsing with the LocalDate & DateTimeFormatter classes. That is what they were built for.
Define formatting patterns to match your expected inputs.
List < String > inputs = List.of( "02/23/2019" , "02-27-2019" , "07|07|2022" );
List < DateTimeFormatter > formatters =
List.of(
DateTimeFormatter.ofPattern( "MM/dd/uuuu" ) ,
DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
);
Collect the results, along with bad (unexpected) inputs.
List < LocalDate > results = new ArrayList <>( inputs.size() );
List < String > faultyInputs = new ArrayList <>();
Loop the inputs. For each string, loop your defined formatters. If one formatter succeeds (matches your input’s format and successfully parses), collect the result. Else if no formatters match the input, collect the faulty input.
for ( String input : inputs )
{
LocalDate ld = null;
for ( DateTimeFormatter formatter : formatters )
{
try
{
ld = LocalDate.parse( input , formatter );
results.add( ld );
break; // Bail-out of looping the formatters. If a format matched, no need to try others.
} catch ( DateTimeParseException e )
{
// Swallow exception. No code needed here.
}
}
if ( Objects.isNull( ld ) ) // If we tried all the expected formats but not matched our input…
{
faultyInputs.add( input );
}
}
Dump to console.
System.out.println( "results:" );
System.out.println( results );
System.out.println( "faultyInputs:" );
System.out.println( faultyInputs );
results:
[2019-02-23, 2019-02-27]
faultyInputs:
[07|07|2022]
ISO 8601
Tip: Educate whoever produces such data about the joys of ISO 8601. Exchanging date-time values textually using localized or invented formats is poor practice.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
\1here inString regex = "[0-9]{1,2}(/|-)[0-9]{1,2}(/|-)[0-9]{4}\1+?