tags:

views:

58

answers:

2

I have a test file that has many lines, each line looks something like:

4:19 PM  5:15 PM  this is some text blah blah

I need a regex that will pull the 2 times and assign them to a variable.

So basically i'm going to be looping through a text file, and extracting the time information from each line and adding up the difference between the two.

I need help with the regex.

+2  A: 

Try this:

 ^([0-9][0-9]*:[0-9][0-9]* (AM|PM))(\t| )+([0-9][0-9]*:[0-9][0-9]* (AM|PM))

The data is in the 1st and 4th match.

Byron Whitlock
+1  A: 

This uses a slightly tweaked regex and adds the differences between dates as you mentioned:

string[] input = { "4:19 PM         5:15 PM  this is some text blah blah",
                "3:00 PM         5:00 PM  text"
        };

// build up pattern
string datePattern = @"(\d+:\d+\s(?:AM|PM))";
string pattern = String.Format("^{0}{1}{2}{3}$",
                               datePattern, @"\s+", datePattern, @"\s+.*");

TimeSpan total = new TimeSpan();
foreach (string text in input)
{
    var match = Regex.Match(text, pattern);
    if (match.Success)
    {
     // skip first group which has entire match
     DateTime dt1 = DateTime.Parse(match.Groups[1].Value);
     DateTime dt2 = DateTime.Parse(match.Groups[2].Value);
     TimeSpan diff = dt2 - dt1;
     total += diff;
    }
}
Console.WriteLine("Total difference: {0}", total);

Result: Total difference: 02:56:00


If you're confident that your data is in the correct format you could make the regex very simple as follows:

    string text = "4:19 PM         5:15 PM  this is some text blah blah";
    string pattern = @"(?<time>\d+:\d+)\s(?<period>AM|PM)";

foreach(Match m in Regex.Matches(text, pattern))
{
    Console.WriteLine("Time: {0} - Period: {1}",
     m.Groups["time"].Value,
     m.Groups["period"].Value
     );
}

If you don't trust the data then you'll probably want something more robust.

Ahmad Mageed
Why the downvotes?
Ahmad Mageed
@homestead: make sure you got the latest edit. I was missing an item in the pattern build up portion and I saw you marked it as the answer before I was done editing.
Ahmad Mageed