EXTRACT A FORMAT OF DATE FROM A STRING

Takeshi Okada

Total Post:89

Points:629
Posted by  Takeshi Okada
C# 
C#
 1662  View(s)
Ratings:
Rate this:

I need to extract a date of birth from a given string. The format is always "ddMMMyy" (for example "22NOV83").

The problem is that there could be other chars before and after the dob. possible inputs are : "DOB: 22NOV83", "CUSTOMER A DOB: 22NOV", "22NOV83 BLA BLA"

I think that by using this Regex:

^\d{2}[a-zA-Z]{3}\d{2}$

I can check if a string mathces a date , But how to check if a part of a string mathces a date and than extract it ?

Any help would be appreciated.

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Extract a format of date from a string

    Hi Takeshi,


    var extractedDates = new List<DateTime>();

      foreach (var s in inputs) {

        var m = Regex.Match(s, @"(\d{2}[A-Za-z]{3}\d{2})");

        if (m.Groups.Count == 1) {

          // No match

          continue;

        }

        try {

          extractedDates.Add(DateTime.Parse(m.Groups[0].Value));

        } catch (FormatException) {

          // Regex matched but something else was wrong, i.e. 98ALS98

        }

      }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!