0

我有所有的行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);
4

3 回答 3

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";

我只是用给定的测试数据编写并测试了上面的方法,并且计算是准确的。

于 2013-03-12T07:56:36.277 回答
0

您的代码有一些错误(在我看来):

  1. string.Join收到 a string[],而您正在传递 a List<string>
  2. 你真的不需要做任何事情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);

下面是输出:

平均数=274

于 2013-03-12T07:57:38.963 回答
-1

我认为您的正则表达式不够正确。您可能还需要考虑将其与以下内容匹配:

"Elapsed Time:.*ms"

要获取数字,您可以截断前 13 个字符和后 2 个字符。然后每行,您可以使用Double.TryParse(因为您自己没有进行任何特殊处理,您可以让该TryParse方法为您执行此操作并保持您自己的代码更清洁)来获取您感兴趣的数字。

您可以检查您的正则表达式以查看它是否在网站上正确匹配,例如http://regexpal.com/

于 2013-03-12T07:45:48.687 回答