Extract a format of date from a string

Total Post:89

Points:629
C# 
C#
 1966  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. 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
        }
      }

      Modified On Apr-04-2018 04:33:22 AM

Answer