简体   繁体   English

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

[英]How to extract specific data out of a complex sentence using regular expression?

I want to scrape data from complex sentence out of a log4net text file with a regular expression. 我想从带有正则表达式的log4net文本文件中抓取复杂句子中的数据。

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

I need the following data: 我需要以下数据:

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

I searched the internet, but I cannot find how to do that in this more complex case. 我搜索了互联网,但是在这种更为复杂的情况下,我找不到解决方法。 Does anyone know a solution? 有人知道解决方案吗?

Thanks a lot, Jordy 非常感谢,乔迪

Try this code... 试试这个代码...

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();

This will give you output like this. 这将给您这样的输出。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM