如何使用c#计算输入文本文件的总运行时间
本文关键字:文件 运行时间 文本 输入 何使用 计算 | 更新日期: 2023-09-27 18:01:50
我想计算"WX GSA搜索"中的总"经过时间"。以下是我的日志文件:
WX搜索=服务器:nomos-scanner.corp.adobe.com用户:vibsharm appGUID:wx运行时间:875ms SaveSearchID:361 wx GSA搜索=服务器:nomos-scanner.corp.adobe.com用户:gulanand appGUID: wx Elapsed时间:890ms SaveSearchID:361 WX GSA Search =服务器:nomos-scanner.corp.adobe.com用户:vibsharm appGUID: wx Elapsed时间:887ms SaveSearchID:361 WX GSA Search =服务器:nomos-scanner.corp.adobe.com用户:gulanand appGUID: wx Elapsed时间:875.5ms SaveSearchID:361 WX GSA Search =服务器:nomos-scanner.corp.adobe.com用户:vibsharm appGUID: wx Elapsed时间:877.6 SaveSearchID女士:361
我写的代码,但不能工作。请检查正则表达式是否正确:
string searchKeyword = "WX GSA Search";
string fileName = @"C:'Users'karan'Desktop'Sample log file.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> users = new List<string>();
Regex regex = new Regex(@"Elapsed Time:'s*(?<timevalue>.*?)+ms");
MatchCollection matches = regex.Matches(x);
foreach (Match match in matches)
{
var user = match.Groups["value"].Value;
if (!users.Contains(time)) users.Add(time);
}
string[] s = users.ToArray();
如果您唯一的问题是正则表达式,请尝试这个。
Regex re = new Regex(@"Elapsed Time:(?<timevalue>'d+(?:'.'d)?)ms");
嗯,你的正则表达式不是完全无效的,但它可以改进。
例如:
Regex regex = new Regex(@"Elapsed Time:'s*(?<value>'d+'.?'d*)'s*ms");
"ms"前的"+"表示任意数量的字符应该重复一次或多次-然后它会尝试任何可能的组合以获得最佳匹配,这需要时间。
我改变了*.?' d +。?'d*只接受带有可选小数的数值。
我也改变了(?<时间价值>…(& lt;值>…所以它匹配你的代码示例。时间价值>
祝你好运
您可以使用String.Split
和Linq
来解析Elapsed time;
TimeSpan elapsedTime = TimeSpan.FromMilliseconds(File.ReadAllLines("c:''log.txt")
.Where(line => line.Contains("Elapsed Time:"))
.Select(line => line.Split(new string[] { "Elapsed Time:"}, StringSplitOptions.RemoveEmptyEntries).Last().Split(' ').First())
.Select<string,double>(time => time.EndsWith("ms") ? double.Parse(time.Replace("ms","").Trim())
: time.EndsWith("s") ? double.Parse(time.Replace("s","").Trim()) * 1000.0 : 0.0 ).Sum());