Finding if a string contains a date and time
Update 2: Found out using DateTime.TryParseExact is a much better way that using Regex Expressions
DateTime myDate;
if (DateTime.TryParseExact(inputString, "dd-MM-yyyy hh:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate))
{
//String has Date and Time
}
else
{
//String has only Date Portion
}
If the format of the date has been defined, you can use Regex to solve it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace RegTest
{
class Program
{
static void Main(string[] args)
{
string testDate = "3214312402-17-2013143214214";
Regex rgx = new Regex(@"\d{2}-\d{2}-\d{4}");
Match mat = rgx.Match(testDate);
Console.WriteLine(mat.ToString());
Console.ReadLine();
}
}
}
string s = " Subject: Current account balances for 21st December 2017 and 2nd January 2019 mnmnm ";//here is u r sample string
s = s.ToLower();
string newStrstr = Regex.Replace(s, " {2,}", " ");//remove more than whitespace
string newst = Regex.Replace(newStrstr, @"([\s+][-/./_///://|/$/\s+]|[-/./_///://|/$/\s+][\s+])", "/");// remove unwanted whitespace eg 21 -dec- 2017 to 21-07-2017
newStrstr = newst.Trim();
Regex rx = new Regex(@"(st|nd|th|rd)");//21st-01-2017 to 21-01-2017
string sp = rx.Replace(newStrstr, "");
rx = new Regex(@"(([0-2][0-9]|[3][0-1]|[0-9])[-/./_///://|/$/\s+]([0][0-9]|[0-9]|[1][0-2]|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec|january|february|march|april|may|june|july|augu|september|october|november|december)[-/./_///:/|/$/\s+][0-9]{2,4})");//a pattern for regex to check date format. For August we check Augu since we replaced the st earlier
MatchCollection mc = rx.Matches(sp);//look for strings that satisfy the above pattern regex
List<DateTime> dates=new List<DateTime>(); //Create a list to store the detected dates
foreach(Match m in mc)
{
string s2=Regex.Replace(m.ToString(), "augu", "august");
dates.Add(DateTime.Parse(s2);
}