O'Reilly logo

Reguläre Ausdrücke Kochbuch by Steven Levithan, Jan Goyvaerts

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

4.5 Klassische Datumsformate exakt validieren

Problem

Sie wollen Datumswerte in den klassischen Formaten mm/dd/yy, mm/dd/yyyy, dd.mm.yy und dd.mm.yyyy validieren. Dabei wollen Sie aber ungültige Datumswerte wie den 31. Februar ausschließen.

Lösung

C#

Monat vor Tag:

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 {
        // Ungültiges Datum
    }
}

Tag vor Monat:

DateTime foundDate; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required