如何使用正则表达式从复杂句子中提取特定数据?

时间:2017-03-17 08:56:15

标签: c# asp.net .net

我想从带有正则表达式的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

我搜索了互联网,但在这个更复杂的案例中我找不到怎么做。有谁知道解决方案?

非常感谢, 约迪

1 个答案:

答案 0 :(得分: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