当我的程序读取并找到某些措辞时,我的应用程序中有多个正则表达式条件。我有一个新的要求是在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();
答案 0 :(得分:1)
可能最快的方法是使用Linq Extensions Library。
它有一个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;
}
答案 1 :(得分:0)
我会得到一个文件的文本字符串,然后使用IndexOf
方法在文件的文本中查找匹配字符串(m.ToString()
)的索引。然后只计算从文本开头到匹配索引的换行符的实例数。使用此计数来确定它发生的行。