从包含字母和数字的文本文件中读取数字

时间:2014-12-09 07:47:31

标签: c# .net logging

我有一个日志文件(txt文件),我想只读取特定的行。这些行包括一组特定的单词,后跟数字。

例如,我想从文件中读取的行为:

  • 10:03总查询花了238.9 mili

  • 10:08总查询花了659.8 mili

如何编写仅需query次执行时间(mili)的代码并添加它们?

我从文本文件中读取的部分只包括“总查询占用”的行,但我从这里停留

3 个答案:

答案 0 :(得分:1)

  1. 从文件中读取文本。 StreamReader可以做到这一点。请查看链接中的示例。
  2. 从文字中获取数字。您可以使用SubstringIndexOf以及Convert.ToDouble。如果你想要幻想,你甚至可以使用Regular Expressions,但这太过分了。
  3. 添加数字。

答案 1 :(得分:0)

Regular Expression应该很容易。我猜这条线是在一个字符串上。

String str_line = "your line from file" ;
Regex regex = new Regex(@"\d.*");
Match match = regex.Match(str_line);
if (match.Success)
{
    //you got the value with "match.Value;"
}

答案 2 :(得分:0)

public decimal ReadMilliseconds()
{
    var lines = File.ReadLines(@"\path\to\file");
    decimal totalMilliseconds = 0;

    foreach (string line in lines)
    {
        var match = Regex.Match(line, @"(?<ms>\d*\.?\d*)\s*mili");

        if (!match.Success) continue;

        decimal value = decimal.Parse(match.Groups["ms"].Value, new CultureInfo("en-US"));

        totalMilliseconds += value;
    }

    return totalMilliseconds;
}