I have the following list of times from today for our jenkins builds, and I want to parse this list and return the date\time of the build.
List (Time since build)
-----------------------
1 day 21 hr
1 day 22 hr
1 mo 14 days
1 mo 14 days
27 days
1 day 6 hr
1 mo 14 days
6 min 13 sec
For example: 1 day 21 hr --> Time from today should return 05/22/2016 09:00:00PM
I put together the following regex version...but it feels very hacky and brittle.
How can I parse this text better.
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string txt = "1 day 21 hr";
string regexday = "(\\d\\s+day)"; // 1 day
string regexdaymultiple = "(\\d\\d\\s+day)"; //10 days
string regexhr = "(\\s+\\d\\s+hr)"; // 1 hr
string regexhrmultiple = "(\\s+\\d\\d\\s+hr)"; // 21 hr
Regex regexdaymatch = new Regex(regexday, RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match matchday = regexdaymatch.Match(txt);
if (matchday.Success)
{
String d1 = matchday.Groups[1].ToString();
DateTime now = DateTime.Now;
Console.Write("("+now.AddDays(-Convert.ToInt32(d1.Replace(" day", "")))+")" + "\n");
}
Regex regexdaymutliplesmatch = new Regex(regexdaymultiple, RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match matchdaymultiple = regexdaymutliplesmatch.Match(txt);
if (matchdaymultiple.Success)
{
String d1 = matchdaymultiple.Groups[1].ToString();
DateTime now = DateTime.Now;
Console.Write("(" + now.AddDays(-Convert.ToInt32(d1.Replace(" day", ""))) + ")" + "\n");
}
Regex regexhrmatch = new Regex(regexhr, RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match matchhr = regexhrmatch.Match(txt);
if (matchhr.Success)
{
String d1 = matchhr.Groups[1].ToString();
DateTime now = DateTime.Now;
Console.Write("(" + now.AddHours(-Convert.ToInt32(d1.Replace(" hr", ""))) + ")" + "\n");
}
Regex regexhrmultiplematch = new Regex(regexhrmultiple, RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match matchhrmultiple = regexhrmultiplematch.Match(txt);
if (matchhrmultiple.Success)
{
String d1 = matchhrmultiple.Groups[1].ToString();
DateTime now = DateTime.Now;
Console.Write("(" + now.AddHours(-Convert.ToInt32(d1.Replace(" hr", ""))) + ")" + "\n");
}
Console.ReadLine();
}
}
}