In: Computer Science
Define a regular expression that will correctly (and exactly) match a valid Gregorian calendar date of the form MM/DD/YYYY (with leading zeroes for single-digit months and days) (and ONLY dates in this format). • Months 1, 3, 5, 7, 8, 10, and 12 have 1–31 days • Months 4, 6, 9, and 11 have 1–30 days • Month 2 (February) has 1–28 days (ignore leap years) • Assume that the year falls into the range 1900–2099 HINT: You may find it helpful to define several patterns and combine them using the alternation operator.
Hi,
Here is the regular expression matching a valid Gregorian calendar date of the form MM/DD/YYYY.
I have combined the various regular expression using the alteration operator |
Please find the regular expression.
^(02(\/)29(\/)(2000|(19|2[0](0[48]|[2468][048]|[13579][26]))))$|^((02(\/)(0[1-9]|1[0-9]|2[0-8])(\/)(19|2[0])[0-9]{2}))$|^(((0[13578]|10|12)(\/)(0[1-9]|[12][0-9]|3[01])(\/)(19|2[0])[0-9]{2}))$|^(((0[469]|11)(\/)(0[1-9]|[12][0-9]|30)(\/)(19|2[0])[0-9]{2}))$
Explanation :
Step 1 :
^(02(\/)29(\/)(2000|(19|2[0](0[48]|[2468][048]|[13579][26]))))$
Step 2 :
^((02(\/)(0[1-9]|1[0-9]|2[0-8])(\/)(19|2[0])[0-9]{2}))$
Matching February 29th in leap years, we also need to match all other days of February (1 – 28) in all years
Step 3:
^(((0[13578]|10|12)(\/)(0[1-9]|[12][0-9]|3[01])(\/)(19|2[0])[0-9]{2}))$
The months January, March, May, July, August, October, and December should match for between 1 and 31 days
Step 4:
^(((0[469]|11)(\/)(0[1-9]|[12][0-9]|30)(\/)(19|2[0])[0-9]{2}))$
The months April, June, September, and November should match for between 1 and 30 days