Home > DeveloperSection > Forums > Extract a format of date from a string
Takeshi Okada
Takeshi Okada

Total Post:89

Points:629
Posted on    March-06-2014 11:06 PM

 C# C# 
Ratings:


 1 Reply(s)
 1364  View(s)
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.



Pravesh Singh

Total Post:411

Points:2881
Posted on    March-06-2014 11:18 PM

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

    }

  }


Don't want to miss updates? Please click the below button!

Follow MindStick