import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?(DEFINE)\n"
+ " (?# Date )\n"
+ " (?# Day ranges )\n"
+ " (?<d_day28>0[1-9]|1\\d|2[0-8])\n"
+ " (?<d_day29>0[1-9]|1\\d|2\\d)\n"
+ " (?<d_day30>0[1-9]|1\\d|2\\d|30)\n"
+ " (?<d_day31>0[1-9]|1\\d|2\\d|3[01])\n"
+ " (?# Month specifications )\n"
+ " (?<d_month28>02)\n"
+ " (?<d_month29>02)\n"
+ " (?<d_month30>0[469]|11)\n"
+ " (?<d_month31>0[13578]|1[02])\n"
+ " (?# Year specifications )\n"
+ " (?<d_year>\\d+)\n"
+ " (?<d_yearLeap>(?:\\d*?(?:(?:(?!00)[02468][048]|[13579][26])|(?:(?:[02468][048]|[13579][26])00))|[48]00|[48])(?=\\D|\\b))\n"
+ " (?# Valid date formats )\n"
+ " (?<d_format>\n"
+ " (?&d_day28)\\/(?&d_month28)\\/(?&d_year)|\n"
+ " (?&d_day29)\\/(?&d_month29)\\/(?&d_yearLeap)|\n"
+ " (?&d_day30)\\/(?&d_month30)\\/(?&d_year)|\n"
+ " (?&d_day31)\\/(?&d_month31)\\/(?&d_year)\n"
+ " )\n"
+ " \n"
+ " (?# Time )\n"
+ " (?# Time properties )\n"
+ " (?<t_period12>(?i)[ap]m|[ap]\\.m\\.(?-i))\n"
+ " (?# Hours )\n"
+ " (?<t_hours12>0\\d|1[01])\n"
+ " (?<t_hours24>[01]\\d|2[0-3])\n"
+ " (?# Minutes )\n"
+ " (?<t_minutes>[0-5]\\d)\n"
+ " (?# Seconds )\n"
+ " (?<t_seconds>[0-5]\\d)\n"
+ " (?# Milliseconds )\n"
+ " (?<t_milliseconds>\\d{3})\n"
+ " (?# Valid time formats )\n"
+ " (?<t_format>\n"
+ " (?&t_hours12):(?&t_minutes):(?&t_seconds)(?:\\.(?&t_milliseconds))?\\ ?(?&t_period12)|\n"
+ " (?&t_hours24):(?&t_minutes):(?&t_seconds)(?:\\.(?&t_milliseconds))?\n"
+ " )\n"
+ " \n"
+ " (?# Datetime )\n"
+ " (?<dt_format>(?&d_format)\\ (?&t_format))\n"
+ ")\n"
+ "\\b(?&dt_format)\\b";
final String string = "29/02/2016 23:10:59 - valid\n"
+ "29/02/2017 23:10:59 - invalid (not leap year)\n"
+ "30/03/2016 23:10:59 - valid";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.COMMENTS);
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