2017-03-17 33 views
0

我想用一個正則表達式從一個log4net文本文件中抽取複雜句子中的數據。如何使用正則表達式從複雜句子中提取特定數據?

4012 09:47:03 INFO QueueController - method GetData(), Start = 15-3-2017 09:47:01, ElapsedSeconds = 1,9023, Task = 7514, Thread = 9 

我需要準備以下數據:

Method = GetData() 
Time = 09:47:03 
Start = 15-3-2017 09:47:01 
ElapsedSeconds = 1,9023 
Task = 7514 
Thread = 9 

我在網上搜索,但我找不到怎麼做,在這種更復雜的情況。有誰知道解決方案?

非常感謝, 的Jordy

+0

你做了一個基本的正則表達式的教程,並試圖自己嗎? –

+0

看起來很直接 –

+0

@Jordy檢查下面的答案,如果這項工作 –

回答

1

試試這個代碼...

string text = "4012 09:47:03 INFO QueueController - method GetData(), Start = 15-3-2017 09:47:01, ElapsedSeconds = 1,9023, Task = 7514, Thread = 9"; 
Regex pattern = new Regex(@"(.*\s+)(?<Time>.*)(\s+INFO QueueController*)(.*method\s+)(?<Method>.*)(, Start\s+)(?<Start>.*)(, ElapsedSeconds =*)(.*\s+)(?<ElapsedSeconds>.*)(, Task =*)(.*\s+)(?<Task>.*)(, Thread =)(.*\s+)(?<Thread>.*)(.*)"); 
Match match = pattern.Match(text); 

string method = match.Groups["Method"].Value; 
string time = match.Groups["Time"].Value; 
string start = match.Groups["Start"].Value.Replace("=",""); 
string elapsed = match.Groups["ElapsedSeconds"].Value; 
string task = match.Groups["Task"].Value; 
string thread = match.Groups["Thread"].Value; 

Console.WriteLine("Method = " + method); 
Console.WriteLine("Time = " + time); 
Console.WriteLine("Start = " + start); 
Console.WriteLine("Elapsed = " + elapsed); 
Console.WriteLine("Task = " + task); 
Console.WriteLine("Thread = " + thread); 
Console.ReadKey(); 

這會給這樣你的輸出。

enter image description here

+0

哇,謝謝你的解釋:-) – Jordy

相關問題