我想使用正则表达式计算“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();
请您参考如下方法:
Linq 方式:
Regex regex = new Regex(@"Elapsed Time:\s*(?<value>\d+\.?\d*)\s*ms");
double totalTime = textLines.Where(line => line.Contains(searchKeyword))
.Select(line => regex.Match(line))
.Where(match => match.Captures.Count > 0)
.Sum(match => Double.Parse(match.Groups["value"].Value));
非 Linq 方式:
Regex regex = new Regex(@"Elapsed Time:\s*(?<value>\d+\.?\d*)\s*ms");
double totalTime = 0;
int count = 0;
foreach (string line in textLines)
{
if (line.Contains(searchKeyword))
{
Match match = regex.Match(line);
if (match.Captures.Count > 0)
{
try
{
count++;
double time = Double.Parse(match.Groups["value"].Value);
totalTime += time;
}
catch (Exception)
{
// not a number
}
}
}
}
double average = totalTime/count;
