[英]Write line from text file if regex finds specific word
當我的程序讀取並找到某些措辭時,我的應用程序中就有多個正則表達式條件。 我有一個新要求,那就是在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()
)的索引。 然后,只需計算從文本開頭到匹配索引的換行符實例的數量即可。 使用此計數來確定發生在哪一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.