2014-10-12 39 views
-3

我有以下日誌行格式,粗體部分正在逐行更改,其餘部分是模式(當然行號和時間也在變化但不相關) 。如何使用正則表達式從字符串中檢索信息

線1732:2014年10月12日09:21:26672 DEBUG [Default_Thread_7] file.name.path.location - [TestStrinn Sys系統/] SpecificNotification消息從網關

到達我希望能夠從這種確切格式的行中檢索「Sys」,數字「」和「特定通知」,它們正在逐行改變變量。

+3

顯示你的努力 – 2014-10-12 09:47:47

回答

3

您可以使用Regex.Matches與以下正則表達式:

(\w+)\/(\d+)\]\s+(\w+) 

代碼:

string input = @"Line 1732: 2014-10-12 09:21:26,672 DEBUG [Default_Thread_7] file.name.path.location - [TestStrinn Sys/1] SpecificNotification message arrived from Gateway"; 
Regex rgx = new Regex(@"(\w+)\/(\d+)\]\s+(\w+)"); 
foreach (Match m in rgx.Matches(input)) { 
    Console.WriteLine(m.Groups[1].Value); 
    Console.WriteLine(m.Groups[2].Value); 
    Console.WriteLine(m.Groups[3].Value); 
} 

C# DEMO

+1

@Unihedron微優化! – 2014-10-12 10:03:45

+0

謝謝,我該如何添加分組?爲了從變量中檢索信息? – user2878881 2014-10-12 10:13:06

+0

@ user2878881檢查出現在 – 2014-10-12 10:14:45

2

使用capturing groups捕捉到你想要的字符。稍後,您可以通過back-referencing引用捕獲的字符。

String input = @"Line 1732: 2014-10-12 09:21:26,672 DEBUG [Default_Thread_7] file.name.path.location - [TestStrinn Sys/1] SpecificNotification message arrived from Gateway"; 
Regex rgx = new Regex(@"^\s*Line\s*\d+:\s*.*?\s*file\.name\.path\.location\s*-\s*\[\s*\S+\s*([^\/]*)\/(\d+)\]\s*(\S+)"); 
foreach (Match m in rgx.Matches(input)) 
{ 
    Console.WriteLine(m.Groups[1].Value); 
    Console.WriteLine(m.Groups[2].Value); 
    Console.WriteLine(m.Groups[3].Value); 
} 

輸出:

Sys 
1 
SpecificNotification 

IDEONE