|
| 1 | +import java.io.BufferedReader; |
| 2 | +import java.io.IOException; |
| 3 | +import java.io.InputStreamReader; |
| 4 | +import java.util.regex.Pattern; |
| 5 | + |
| 6 | +/** |
| 7 | + * Parse a given date in dd/yyyy/mm format with different difficulties |
| 8 | + */ |
| 9 | +public class DateValidation { |
| 10 | + |
| 11 | + /** |
| 12 | + * Very naive approach. |
| 13 | + */ |
| 14 | + public static Pattern EASY_FORMAT = Pattern.compile("\\d\\d/\\d\\d\\d\\d/\\d\\d"); |
| 15 | + |
| 16 | + /** |
| 17 | + * Let's split up into different cases, i.e. different months. |
| 18 | + */ |
| 19 | + public static Pattern MEDIUM_FORMAT = Pattern.compile("" |
| 20 | + + "(((0[1-9])|([1-2][0-9]))/\\d\\d\\d\\d/02" // February |
| 21 | + + "|((0[1-9])|([1-2][0-9])|(3[0-1]))/\\d\\d\\d\\d/(01|03|05|07|08|10|12)" // Months with 31 days |
| 22 | + + "|((0[1-9])|([1-2][0-9])|(30))/\\d\\d\\d\\d/(04|06|09|11))" // Months with 30 days |
| 23 | + ); |
| 24 | + |
| 25 | + /** |
| 26 | + * For the hard format, take into account that a year is a leap year if it is divisible by 4, but not by 100. |
| 27 | + * However, if the year is divisible by 400, it will nevertheless be counted as a leap year. |
| 28 | + */ |
| 29 | + public static Pattern HARD_FORMAT = Pattern.compile("" |
| 30 | + + "(29/" // 29th day |
| 31 | + + "((([0-9]{2})(04|08|[2468][048]|[13579][26]))|" // First two numbers are arbitrary; if the last two |
| 32 | + // numbers are divisible by 4, but are not 00 |
| 33 | + // So, the year is divisible by 4, but not 100 |
| 34 | + + "(00|04|08|[2468][048]|[13579][26])00)" // If the first two numbers are divisible by 4 and the last two |
| 35 | + // are 00. So, the year is divisible by 400 |
| 36 | + + "/02" // February |
| 37 | + + "|((0[1-9])|(1[0-9])|(2[0-8]))/\\d\\d\\d\\d/02" // "Normal" Februaries |
| 38 | + + "|((0[1-9])|([1-2][0-9])|(3[0-1]))/\\d\\d\\d\\d/(01|03|05|07|08|10|12)" // Months with 31 days |
| 39 | + + "|((0[1-9])|([1-2][0-9])|(30))/\\d\\d\\d\\d/(04|06|09|11))" // Months with 30 days |
| 40 | + ); |
| 41 | + |
| 42 | + public static void main(String[] args) throws IOException { |
| 43 | + System.out.println("Starting the Regex Date Validation..."); |
| 44 | + |
| 45 | + try (InputStreamReader isr = new InputStreamReader(System.in); |
| 46 | + BufferedReader in = new BufferedReader(isr)) { |
| 47 | + System.out.print("Enter date to validate: "); |
| 48 | + String date = in.readLine(); |
| 49 | + |
| 50 | + System.out.println("Matches dd/yyyy/mm format: " + EASY_FORMAT.matcher(date).matches()); |
| 51 | + System.out.println("Matches also days per month: " + MEDIUM_FORMAT.matcher(date).matches()); |
| 52 | + System.out.println("Matches also leap years: " + HARD_FORMAT.matcher(date).matches()); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | +} |
0 commit comments