如何匹配包含和不包含关键字的多行日志条目(正则表达式)

时间:2015-03-18 12:38:50

标签: c# .net regex multiline

我的日志文件如下所示:

 *** DEBUG 2015-03-18 12:11:46.678 [sendTaskResponse] ID2200*     
 Creating object GUID=6b7582ba-eb8b-4084-b726-26901827f150

 *** ERROR 2015-03-18 12:11:46.912 [        23] ID2543      
 Details:
 System.IO.IOException: Incorrect WPDU: 22354
    w Devices.DlmsConnection.Connect(DeviceE device, AGPRSKeysAssocEnum user) in d:\current\csharp\AProject\ADriver\Devices\DeviceE.cs:row 1921
    w Devices.Device.Connect(AGPRSKeysAssocEnum user) in d:\A\current\csharp\AProject\ADriver\Devices\DeviceE.cs:row 522
    w A.Devices.DeviceE.InitTask(DelegatedObjectTask thisTask) in d:\A\current\csharp\AProject\ADriver\Devices\DeviceE.cs:row 252

 *** DEBUG 2015-03-18 12:11:46.929 [sendStatus] ID2200*     
 Sending XML N.F6.Data.F6ObjectStatusData

 <?xml version="1.0" encoding="utf-16"?>
 <F6ObjectStatusData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <sourceId>2200</sourceId>
   <status>4</status>
   <statusText> </statusText>
   <timestamp>2015-03-18T11:11:46.6237699Z</timestamp>
 </F6ObjectStatusData>
 <?xml version="1.0" encoding="utf-16"?>
 <F6ObjectStatusData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <sourceId>2202</sourceId>
   <status>4</status>
   <statusText>Device ready</statusText>
   <timestamp>2015-03-18T12:11:21.7213456+01:00</timestamp>
 </F6ObjectStatusData>

 *** DEBUG 2015-03-18 12:11:47.263 [sendStatus] ID2200*     
 Posted Objects Count=2


1)我需要获得这4个日志条目中的每一个 所以从***开始从行开始 并且每个下一行都不以***为开头 2)我需要包含一些关键字的日志条目(例如word&#34; AGPRSKeysAssocEnum&#34; - 第2个日志条目)
必须使用正则表达式模式完成。

1 个答案:

答案 0 :(得分:3)

 string text = fctb.Text;
 string strRegex = @"(\*\*\* (.*?)(?=\*\*\* |\z))";                      // ANSWER #1 
 //string strRegex = @"(\*\*\* [^\*]+AGPRSKeysAssocEnum.*?)(?=\*\*\*|\z)"; // ANSWER #2
 Regex myRegex = new Regex(strRegex, RegexOptions.Singleline);
 MatchCollection m = myRegex.Matches(text);
 foreach (Match sm in m)
 {
    System.Diagnostics.Debug.WriteLine(sm.Groups[1].Value);
    System.Diagnostics.Debug.WriteLine(new String('-', 100));
 }

带有关键字的搜索条目首先拆分日志,然后将regex likethis应用于每个日志,例如:

string text = "Your log text";
IEnumerable<string> splittedLog = GetEntriesForLog(text);
string strRegex = @".*?AGPRSKeysAssocEnum.*|\z";
Regex myRegex = new Regex(strRegex, RegexOptions.ExplicitCapture | RegexOptions.Singleline);

var entries = splittedLog.Where(entry => myRegex.IsMatch(entry)).ToList();