You should analyze the dates within this string to ensure they are valid dates, so avoid future problems.
With a regular expression and using the method Tryparseexact it is possible to extract the date more safely, however, I did not run all the tests so I suggest you test the function below with several entries to check for unwanted results.
Image of the regex:
Function code:
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;
}
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 on .NET Fiddle.
Sources:
Regex to match Date
Get Date from String
Very good, but the application already does this validation, but thank you very much !!!
– Caio Vinícius