若正则表达式找到特定单词,则从文本文件中写入一行

本文关键字:文件 一行 文本 正则表达式 单词 | 更新日期: 2023-09-27 18:28:31

当我的程序读取并找到某些措辞时,我的应用程序中有多个regex条件。我有一个新的要求,要在IF语句中向Message.Body写出这一行。我只需要回顾15分钟。我该如何发送带有此措辞的行?

这是发生错误之前日志文件的开头:10/30/2014 7:19:06 AM 19993108 There is not enough space on the disk:我最需要的是时间之后和消息之前的号码。

//This section looks for matching the words
Regex regex2 = new Regex("(?<time>.+(AM|PM)).*There is not enough space on the disk.");
var lastFailTime2 = File.ReadLines(file)
.Select(line => regex2.Match(line))
.Where(m => m.Success) // take only matched lines
.Select(m => DateTime.Parse(m.Groups["time"].Value))
.DefaultIfEmpty() // DateTime.Min if no failures
.Max();

若正则表达式找到特定单词,则从文本文件中写入一行

可能最快的方法是使用Linq扩展库。

它有一个ElementAtMax()扩展方法,它返回出现最大选定值的元素(与返回所述最大值的LINQ Max()相反)。

编辑:如果出于某些原因,你需要避免在代码中添加第三方库,那么自己编写一个库并没有那么复杂(尽管如果可能的话,可以使用前者——这基本上是在重新发明轮子):

public static TSource ElementAtMax<TSource, TComparable>(
    this IEnumerable<TSource> source,
    Func<TSource, TComparable> selector) where TComparable : IComparable
{
    /* check for empty/null arguments */
    TSource result = default(TSource);
    TComparable currentMax = null;
    bool firstItem = true;
    foreach (var item in source)
    {
       if (firstItem)
       {
          result = item;
          currentMax = selector(item);
          firstItem = false;
          continue;
       }
       var nextVal = selector(item);
       if (currentMax != null && currentMax.CompareTo(nextVal) > 0)
          continue;
       currentMax = nextVal;
       result = item;
    }
    return result;
}

我将获得文件文本的字符串,然后使用IndexOf方法在文件文本中找到匹配字符串(m.ToString())的索引。然后,只需计算从文本开头到匹配索引的换行符实例数。使用此计数来确定发生在哪一行。