You should analyze dates within this string to ensure they are valid dates, thus avoiding future problems.
With a regular expression and using the method TryParseExact is However, I did not run all the tests so I suggest you test the function below with several entries to check for unwanted results.
Regex illustration image:
Functioncode:
List<string>ExtrairDatas(stringstr){varregex=newRegex(@"(?:(?:(?:(?:0?[13578])|(1[02]))/31/(19|20)?\d\d)|(?:(?:(?:0?[13-9])|(?:1[0-2]))/(?:29|30)/(?:19|20)?\d\d)|(?:0?2/29/(?:19|20)(?:(?:[02468][048])|(?:[13579][26])))|(?:(?:(?:0?[1-9])|(?:1[0-2]))/(?:(?:0?[1-9])|(?:1\d)|(?:2[0-8]))/(?:19|20)?\d\d))");
var datas = new List<string>();
foreach(Match m in regex.Matches(str))
{
DateTime dt;
if (DateTime.TryParseExact(m.Value,"dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) datas.Add(dt.ToString("dd/MM/yyyy"));
}
return datas;
}
Complete code:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using static System.Console;
public class Program
{
public static void Main()
{
string teste = "Aprovados por autorizantes da aplicação -> 02/03/2018";
ExtrairDatas(teste).ForEach(d => WriteLine(d));
}
static List<string> ExtrairDatas(string str)
{
var regex = new Regex(@"(?:(?:(?:(?:0?[13578])|(1[02]))/31/(19|20)?\d\d)|(?:(?:(?:0?[13-9])|(?:1[0-2]))/(?:29|30)/(?:19|20)?\d\d)|(?:0?2/29/(?:19|20)(?:(?:[02468][048])|(?:[13579][26])))|(?:(?:(?:0?[1-9])|(?:1[0-2]))/(?:(?:0?[1-9])|(?:1\d)|(?:2[0-8]))/(?:19|20)?\d\d))");
var datas = new List<string>();
foreach(Match m in regex.Matches(str))
{
DateTime dt;
if (DateTime.TryParseExact(m.Value,"dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) datas.Add(dt.ToString("dd/MM/yyyy"));
}
return datas;
}
}
See working at .NET Fiddle .
Sources:
Regex to match Date
Get Date from String