Reading values ​​from a file using regular expression or other parsing

I have a file that logs timestamped values. I have to read a specific value after a certain time.

for instance

File has

2013-03-03 19:08:22    car   2001 Ford
2013-03-03 19:08:27    Truck 2012 Chevy
2013-03-03 19:08:44    car 2008   Honda
2013-03-03 19:08:55    car 2011   Ford
2013-03-03 19:09:21    car 2005   Nissan
2013-03-03 19:08:29    car 2003   Cadillac
2013-03-03 19:08:32    car 2009   Jeep
2013-03-03 19:08:52    car 2007   Suburban

I want to read the time of the first Chevy instance, than add 40 seconds to it, than to read which Ford will appear after this time.

So based upon the above log
First Chevy is at   19:08:27  
Add 40 seconds      19:09:07
Now Read first Ford that shows up after 19:09:07  in this case that would be one at 19:08:55

I am new to regex, I don’t know exactly how to write it. Thanks

+1
source share
1 answer

First, I really do not suggest you use Regex for this, but here you can use:

var data =  @"2013-03-03 19:08:22    car   2001 Ford
2013-03-03 19:08:27    Truck 2012 Chevy
2013-03-03 19:08:44    car 2008   Honda
2013-03-03 19:08:55    car 2011   Ford
2013-03-03 19:09:21    car 2005   Nissan
2013-03-03 19:08:29    car 2003   Cadillac
2013-03-03 19:08:32    car 2009   Jeep
2013-03-03 19:08:52    car 2007   Suburban";

string regex =
    @"(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})[^\n\r]+?Chevy.+?(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})[^\n\r]+?Ford";
var m = Regex.Match(data, regex, RegexOptions.Singleline);

Console.WriteLine("Chevy date: {0}", DateTime.Parse(m.Groups[1].Value));
Console.WriteLine("Ford date: {0}", DateTime.Parse(m.Groups[2].Value));

The above code will print:

Chevy date: 2013-03-03 19:08:27
Ford date: 2013-03-03 19:08:55

, , 40 . , AddSeconds(..) DateTime.

: :

  • (\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}) DateTime
  • [^\n\r]+?Chevy "Chevy"
  • .+? ...
  • (\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}) , DateTime...
  • [^\n\r]+?Ford... ""

. , :

using (var reader = new StreamReader(@"C:\file-here.txt")) {
    bool chevyFound = false;
    while (!reader.EndOfStream) {
        var line = reader.ReadLine().Trim();

        if (chevyFound && line.EndsWith("Ford")) {
            var fordDate = DateTime.Parse(line.Substring(0, 19));
            Console.WriteLine("Ford Date: {0}", fordDate);
            break;
        }

        if (line.EndsWith("Chevy")) {
            var chevyDate = DateTime.Parse(line.Substring(0, 19));
            Console.WriteLine("Chevy Date: {0}", chevyDate);
            chevyFound = true;
        }
    }
}

, - , , DateTimes ( Substring(0,19)). :

var chevyDate = DateTime.Parse(Regex.Match(line, "^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}").Value)
0

All Articles