I'm working on a C# project and I need to parse and extract some dates from some strings. Theese are my strings:
dalle ore 19.30 del 04.02.2016 alle ore 19.30 del 06.02.2016
dalle ore 19.30 del 06.02.2016 alle ore 19.30 del 08.02.2016
...
For each one I'd like to extract the two dates (ex. 04.02.2016 06.02.2016) and save to two variables. Next I'll parse them to create two DateTime objects. Now I'm using this code:
public static string isdate(string input)
{
Regex rgx = new Regex(@"\d{2}.\d{2}.\d{4}");
Match mat = rgx.Match(input);
if(mat.Success)
return mat.ToString();
else return null;
}
With this code i can extract the first date but not the second one. How can I improve my regular expression? Thanks!
Try code below
static void Main(string[] args)
{
string[] inputs = {
"dalle ore 19.30 del 04.02.2016 alle ore 19.30 del 06.02.2016",
"dalle ore 19.30 del 06.02.2016 alle ore 19.30 del 08.02.2016"
};
string pattern = @"(?'hour'\d\d).(?'minute'\d\d)\sdel\s(?'day'\d\d.\d\d.\d\d\d\d)";
foreach (string input in inputs)
{
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
TimeSpan time = new TimeSpan(int.Parse(match.Groups["hour"].Value), int.Parse(match.Groups["minute"].Value), 0);
DateTime date = DateTime.ParseExact(match.Groups["day"].Value, "MM.dd.yyyy", CultureInfo.InvariantCulture);
Console.WriteLine("Time : {0}", date.Add(time));
}
}
Console.ReadLine();
}
Ok the solution by jdwend is good but the problem is that between HH.mm and the date could be several spaces and characters. several times is in this form: HH:mm del dd.MM.YYYY but sometimes is in this form dd.MM.YYYY del dd.MM.YYYY . Do You think is still possible to parse all data with one regexp or do I have to tokenize the string? Thank U so much!