我有textLines1
中的所有行,我想计算所有这些行的平均经过时间。我试过这个正则表达式。但它给了我错误的计算。
日志文件格式:
INFO: WX ADVSearch = Server:testserver Entity:BUG User:acucu Elapsed Time:274ms
INFO: WX ADVSearch = Server:testserver Entity:BUG User:acucu Elapsed Time:274ms
我尝试的代码是:
List<string> textLines1 = new List<string>(users);
string x = string.Join(",", textLines1);
Regex regex = new Regex(@"Elapsed Time:\s*(?<value>\d+\.?\d*)\s*ms");
Match match = regex.Match(x);
double totalTime = 0;
int count = 0;
foreach (string line in textLines1)
{
if (match.Captures.Count > 0)
{
try
{
count++;
double time = Double.Parse(match.Groups["value"].Value);
totalTime += time;
}
catch (Exception)
{
// no number
}
}
}
double average = totalTime / count;
Console.WriteLine("ADVAverage=" + average);
答案 0 :(得分:1)
private static void CalculateTotalTime()
{
Regex pattern = new Regex(@"INFO:.+Elapsed Time:(?<milliseconds>\d+(\.\d{1,2})?)ms");
double totalMilliseconds = (from Match match in pattern.Matches(input)
let milliseconds = double.Parse(match.Groups["milliseconds"].Value)
select milliseconds).Sum();
TimeSpan elapsed = TimeSpan.FromMilliseconds(totalMilliseconds);
Console.WriteLine("{0:D2}:{1:D2}:{2:D2}:{3:D3}", elapsed.Hours, elapsed.Minutes, elapsed.Seconds, elapsed.Milliseconds);
}
private const string input =
"INFO: WX ADVSearch = Server:yukon.corp.adobe.com Entity:BUG User:acucu Elapsed Time:274ms\n" +
"INFO: WX ADVSearch = Server:yukon.corp.adobe.com Entity:BUG User:acucu Elapsed Time:27.5ms\n" +
"INFO: WX ADVSearch = Server:yukon.corp.adobe.com Entity:BUG User:acucu Elapsed Time:500.55ms";
我刚用给定的测试数据编写并测试了上述方法,计算结果准确无误。
答案 1 :(得分:0)
您的代码有一些错误(在我看来):
string.Join
收到string[]
,您传递了List<string>
。string.Join
。相反,只需遍历每一行,并捕获每一行中的匹配。请参阅以下代码:
//I don't think you have to do this. Instead, you can iterate through `users`
string[] textLines1 = new List<string>(users).ToArray();
double totalTime = 0;
int count = 0;
//For each line
foreach (string line in textLines1) {
//Here we match against this line
var m = Regex.Match(line, @"Elapsed Time:\s*(?<value>\d+\.?\d*)\s*ms");
//If it matched...
if (m.Success) {
try
{
count++;
double time = Double.Parse(m.Groups["value"].Value);
totalTime += time;
}
catch (Exception)
{
// no number
}
}
}
double average = totalTime / count;
Console.WriteLine("ADVAverage=" + average);
以下是输出:
ADVAverage = 274
答案 2 :(得分:-1)
我认为你的正则表达式不够正确。您可能还想考虑以下匹配:
"Elapsed Time:.*ms"
要获取该号码,您可以截断前13个字符和后2个字符。
然后每行,您可以使用Double.TryParse
(因为您自己没有进行任何特殊处理,您可以让TryParse
方法为您执行此操作并保持您自己的代码更清洁)以获取您的数字感兴趣的。
您可以查看正则表达式,看看它是否在网站上正确匹配,例如http://regexpal.com/。