使用 C# 从文本文件中提取特定文本

Extract Specific Text from a Text File Using C#

我想使用正则表达式从文本文件中仅提取 IP 地址。

Interface: 192.168.8.100 --- 0x11
Internet Address    Physical Address    Type
  192.168.8.1         a8-7d-12-c6-73-2c   dynamic
  192.168.8.255       ff-ff-ff-ff-ff-ff   static
  224.0.0.22          01-00-5e-00-00-16   static
  224.0.0.251         01-00-5e-00-00-fb   static
  224.0.0.252         01-00-5e-00-00-fc   static
  239.255.102.18      01-00-5e-7f-66-12   static
  239.255.255.250     01-00-5e-7f-ff-f1   static
  255.255.255.255     ff-ff-ff-ff-ff-ff   static

例如,在这张图片中,我只想要与这个字符串 192.168 匹配的 IP 地址。等等。 并希望将每个匹配项保存在一个单独的变量中。

            string path = @"C:\Test\Result.txt";
            StringBuilder buffer = new StringBuilder();

            using (var sr = new StreamReader(path))
            {
                while (sr.Peek() >= 0)
                {
                    if (Regex.IsMatch(sr.ReadLine(), "192"))
                        buffer.Append(sr.ReadLine());

                }
            }
            Console.WriteLine(buffer.ToString());

我试过这段代码,但结果不是很有说服力。

此外,正如我们所见,这段代码并未提供所有匹配项。

我也试过这个代码

            // Spilt a string on alphabetic character  
            string azpattern = "[a-z]+";
            string str ="192.168.1.1 tst sysy 192.168.3.1";



            string[] result = Regex.Split(str, azpattern, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(500));
            for (int i = 0; i < result.Length; i++)
            {
                Console.Write("{0}", result[i]);
                if (i < result.Length - 1)
                    Console.Write("\n");
            }

但是输入导致了我的问题。我不知道如何使用文本文件作为输入。 还有,这个结果又不是很有说服力

无论如何,有人可以帮我得到这个表格的结果吗?

String IP1 = 192.168.0.1;
String IP2 = 192.168.0.2;

依此类推,直到文件中没有其他 192.... 如果我们在阅读时跳过前 3 行也很好,因为它们在我的场景中毫无用处。

我认为这应该足够了:

const string ipPattern = @"^\s*(192\.168\.\d{1,3}\.\d{1,3})";
var ipRegex = new Regex(ipPattern);

var ipAddresses192168 = File.ReadAllLines(@"C:\Test\Result.txt")
    .Skip(3) // Skip 3 lines
    .Where(line => ipRegex.IsMatch(line))
    .Select(line => ipRegex.Match(line).Groups[1].Value);

foreach (var ipAddress in ipAddresses192168)
{
    Console.WriteLine(ipAddress);
}

它只提取以192.168开头的ip地址并跳过3个第一行。