This will extract, parse and print all the dates in the input text:
var regex = new Regex(@"\b\d{2}\.\d{2}.\d{4}\b");
foreach(Match m in regex.Matches(inputText))
{
DateTime dt;
if (DateTime.TryParseExact(m.Value, "dd.MM.yyyy", null, DateTimeStyles.None, out dt))
Console.WriteLine(dt.ToString());
}
Now, if you just need the first date, you can do this:
static DateTime? GetFirstDateFromString(string inputText)
{
var regex = new Regex(@"\b\d{2}\.\d{2}.\d{4}\b");
foreach(Match m in regex.Matches(inputText))
{
DateTime dt;
if (DateTime.TryParseExact(m.Value, "dd.MM.yyyy", null, DateTimeStyles.None, out dt))
return dt;
}
return null;
}
Note that the method returns nullable DateTime, so that it can return null when the string does not contain a date.
source
share