import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^\n\n"
+ "# Validate the basic structure\n"
+ "(?=\\d{1,4}\\/\\d{1,4}\\/\\d{1,4}$)\n\n"
+ "# The below subexpression matches a leap year\n"
+ "# This will be useful later when checking Feb 29th\n"
+ "(?<leap>0*$|\\d*(?:[13579][26]|(?:\\b|[02468])[048])(?:00|(?<!00))$){0}\n\n"
+ "# Match and capture a month, saving a 30-day month or Feb for later reference\n"
+ "0*(?<month>(?<thirty>9|4|6|11)|(?<feb>2)|1[02]|[13578])\\/\n\n"
+ "# If Feb was matched and 29 appears, check for a leap year\n"
+ "0*(?<day>[1-9]|1\\d|2[0-8]|(?(feb)29(?=\\/(?&leap))|(?:29|(?(thirty)30|3[01]))))\\/\n\n"
+ "# Match and capture a year\n"
+ "(?:0\\B)*(?<year>\\d+)\n\n"
+ "$";
final String string = "1/25/2018\n"
+ "3/11/2119\n"
+ "6/8/224\n"
+ "6/54/1996\n"
+ "2/29/2004\n"
+ "2/29/1900";
final Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS | Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html