解析我的进程输出中的字符串表

时间:2012-12-14 20:04:24

标签: c#

我从流程输出中收到此表到List<string>

enter image description here

List<string> list = new List<string>();
StreamReader reader = tsharkProcess.StandardOutput;

            while (!reader.EndOfStream)
            {
                string read = reader.ReadLine();
                list.Add(read);
            }

解析此表只显示ip地址,值和父母的最佳方法是什么?

3 个答案:

答案 0 :(得分:1)

如果行以制表符分隔

,这将立即读取ipAddress,值和百分比
using(StreamReader reader = tsharkProcess.StandardOutput)
{
   while (!reader.EndOfStream)
   {
       string[] values = reader.ReadLine().Split('\t');
       if (values.Length == 4)
       {
           string ipAddress = values[0];
           string value = values[1];
           string percentage = values[3];
           ...
       }
   }
}

如果没有,则可以使用RegEx完成。

using(StreamReader reader = tsharkProcess.StandardOutput)
{
   while (!reader.EndOfStream)
   {
       string row = reader.ReadLine();
       string[] values = Regex.Split(row, @"\s+", RegexOptions.None);
       if (values.Length == 4)
       {
           string ipAddress = values[0];
           string value = values[1];
           string percentage = values[3];
           ...
       }
   }
}

硬核RegEx解决方案。

public class MyClass
{
    // Lots of code....

    private static Regex regexRowExtract = new Regex(@"^\s*(?<ip>\d+\.\d+\.\d+\.\d+)\s*(?<value>\d+)\s+(?<rate>\d+\.?\d*)\s+(?<percentage>\d+\.?\d*)%\s*$", RegexOptions.Compiled);

    public void ReadSharkData()
    {
        using(StreamReader reader = tsharkProcess.StandardOutput)
        {
            while (!reader.EndOfStream)
            {
                string row = reader.ReadLine();
                Match match = regexRowExtract.Match(row);
                if (match.Success)
                {
                    string ipAddress = match.Groups["ip"].Value;
                    string value = match.Groups["value"].Value;
                    string percentage = match.Groups["percentage"].Value;

                    // Processing the extracted data ...
                }
            }
        }
    }
}

对于Regex解决方案,您应该使用:

using System.Text.RegularExpressions;

答案 1 :(得分:0)

我会选择正则表达式,也许不是最好的解决方法。

IP的正则表达式

\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b

我没有搜索任何正则表达式百分比,但我认为它不会那么难。

答案 2 :(得分:0)

您可以创建一个正则表达式,它将匹配行中的不同值,并逐行解析文件。它应该相对容易,因为所有的值都用空格分隔。