1

我正在尝试在文本 /.log 文件中搜索关键字“DEBUG 2018-06-04T13:27:15+00:00”一旦找到最后一个关键字 DEBUG,然后我想比较日期和时间到当前日期 $ 时间,如果超过 10 分钟输出失败。

4

1 回答 1

2

您可以使用以下命令提取所有匹配的子字符串Regex.Matches

String text = File.ReadAllText(@"C:\My\File\Path.txt");

MatchCollection matches = Regex.Matches(
    text,
    @"DEBUG (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+\d{2}:\d{2})"
)

检查最后一场比赛:

if (matches.Count > 0) {
    Match last = matches[matches.Count - 1];
    DateTime dt = DateTime.Parse(last.Groups[1].Value);

    if (DateTime.Now > dt.AddMinutes(10)) {
         Console.WriteLine("Last date entry is older than 10 minutes ago: {0}", dt);
    }
}

或遍历所有匹配项:

foreach (Match match in matches) {
    // Parse the date string in the matched text:
    DateTime dt = DateTime.Parse(match.Groups[1].Value);

    if (DateTime.Now > dt.AddMinutes(10)) {
        // Date is older than 10 minutes ago
        Console.WriteLine("Date is older than 10 minutes ago: {0}", dt);
    }
}
于 2018-06-09T19:39:42.623 回答