我想使用正则表达式计算“GSA 搜索”的总“经过时间”。
我的日志文件格式为:
WX Search = Server:nomos-scanner.corp.com User:vibsharm appGUID: wx Elapsed Time: 975ms SaveSearchID:361
WX Search = Server:nomos-scanner.corp.com User:vibsharm appGUID: wx Elapsed Time: 875ms SaveSearchID:361
GSA Search = Server:nomos-scanner.corp.com User:gulanand appGUID: wx Elapsed Time:890ms SaveSearchID:361
GSA Search = Server:nomos-scanner.corp.com User:vibsharm appGUID: wx Elapsed Time:887ms SaveSearchID:361
GSA Search = Server:nomos-scanner.corp.com User: gulanand appGUID: wx Elapsed Time: 875.5ms SaveSearchID:361
GSA Search = Server:nomos-scanner.corp.com User:vibsharm appGUID: wx Elapsed Time:877.6ms SaveSearchID:361
我的代码:
string searchKeyword = "WX GSA Search";
string fileName = @"C:\Users\karansha\Desktop\sample log.txt";
string[] textLines = File.ReadAllLines(fileName);
List<string> results = new List<string>();
foreach (string line in textLines)
{
if (line.Contains(searchKeyword))
{
results.Add(line);
}
}
string x = string.Join(",", results);
List<string> value = new List<string>();
Regex regex = new Regex(@"Elapsed Time:\s*(?<value>\d+\.?\d*)\s*ms");
MatchCollection matches = regex.Matches(x);
foreach (Match match in matches)
{
var time = match.Groups["value"].Value;
if (value.Contains(time)) value.Add(time);
}
int ElapsedTime = value.Count();
Console.WriteLine(ElapsedTime);
// keep screen from going away
// when run from VS.NET
Console.ReadLine();