This will extract, parse and print all dates in the input text:
var regex = new Regex(@"d{2}.d{2}.d{4}");
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 want the first date, you can do that:
static DateTime? GetFirstDateFromString(string inputText)
{
var regex = new Regex(@"d{2}.d{2}.d{4}");
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 a nullable DateTime
, so that it can return null when the string contains no date.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…