August 2012
Intermediate to advanced
609 pages
19h 16m
English
You want to validate dates in the traditional formats mm/dd/yy, mm/dd/yyyy, dd/mm/yy, and dd/mm/yyyy, as shown in Recipe 4.4. But this time, you also want to weed out invalid dates, such as February 31st.
The first solution requires the month to be specified before the day. The regular expression works with a variety of flavors:
^(?<month>[0-3]?[0-9])/(?<day>[0-3]?[0-9])/(?<year>(?:[0-9]{2})?[0-9]{2})$| Regex options: None |
| Regex flavors: .NET, Java 7, XRegExp, PCRE 7, Perl 5.10 |
This is the complete solution implemented in C#:
DateTime foundDate;
Match matchResult = Regex.Match(SubjectString,
"^(?<month>[0-3]?[0-9])/(?<day>[0-3]?[0-9])/" +
"(?<year>(?:[0-9]{2})?[0-9]{2})$");
if (matchResult.Success) {
int year = int.Parse(matchResult.Groups["year"].Value);
if (year < 50) year += 2000;
else if (year < 100) year += 1900;
try {
foundDate = new DateTime(year,
int.Parse(matchResult.Groups["month"].Value),
int.Parse(matchResult.Groups["day"].Value));
} catch {
// Invalid date
}
}The second solution requires the day to be specified before the month. The only difference is that we’ve swapped the names of the capturing groups in the regular expression.
^(?<day>[0-3]?[0-9])/(?<month>[0-3]?[0-9])/(?<year>(?:[0-9]{2})?[0-9]{2})$| Regex options: None |
| Regex flavors: .NET, Java 7, XRegExp, PCRE 7, Perl 5.10 |
The C# code is unchanged, except for the regular expression:
DateTime foundDate; Match matchResult = Regex.Match(SubjectString, ...