如何计算行数并在结果前面的每一行打印行号?

时间:2013-12-31 20:51:37

标签: c# regex richtextbox

我正在尝试将我的方式改为文本文件,以便在第二个richtextbox中搜索,计算和显示结果,因为我们在整个文本文件中找到了我们要查找的内容(已加载到第一个richtextbox中)< / p>

int totalOUTgroups = Lines(ofd.FileName)
  .Select(line => Regex.Matches(line, @"access-group\s+\w+\s+out\s+interface\s+\w+").Count)
  .Sum();

// then list the count into the box or save it for later reports   
if (totalOUTgroups > 0)
{
    richTextBox2.SelectionFont = new Font("Courier New", 8);
    richTextBox2.AppendText(">>>ACls using OUT are out: " + "\u2028");
    richTextBox2.AppendText(">>>Total found: " + totalOUTgroups.ToString() + "\u2028");
    string config = File.ReadAllText(ofd.FileName);
    string accessgroupOut = @"(access-group\s+\w+\s+out\s+interface\s+\w+)";

    Regex ace = new Regex(accessgroupOut, RegexOptions.IgnoreCase | RegexOptions.Multiline);
    Match findGroup = ace.Match(config);

    // Let's count each line we found a match and print that on our richtextbox2.
    int counter = 1;
    string line;
    System.IO.StreamReader file = new System.IO.StreamReader(ofd.FileName);

    while ((line = file.ReadLine()) != null)
    {
        if (line.Contains(findGroup.Value))
        {
             foreach (Match findgroup in ace.Matches(config))
             {                                      
                 richTextBox2.AppendText("Line:" + " " + counter.ToString() + " "+ "" + findgroup.Value + "\u2028");
             }  
        }

    counter++;
    }
}

好的,我想要的输出应该是:

>>>ACLs using OUT are out:
>>>Total Found: 3
Line: 15 access-group myaclname OUT interface outside.12
Line: 16 access-group youraclname OUT interface outside.1
Line: 17 access-group aclname OUT interface outside

现在我拥有的是:

>>>ACLs using OUT are out:
>>>Total Found: 3
Line: 15 access-group myaclname OUT interface outside.12
Line: 15 access-group youraclname OUT interface outside.1
Line: 15 access-group aclname OUT interface outside

我是一名网络工程师,C#不是我的专业领域,虽然我觉得它很吸引人,每天都在了解它,特别是在这里。

1 个答案:

答案 0 :(得分:0)

最简单的方法是读取每一行并使计数器保持跟踪。

using (StreamReader r = new StreamReader("test.txt")) 
{
    int counter = 1;
    string line = r.ReadLine();
    while (line != null) 
    {
        Console.WriteLine (counter.ToString() + ": " + line);
        counter++;
        line = r.ReadLine ();
    }
}
相关问题