【问题标题】:Extract Specific Text from a Text File Using C#使用 C# 从文本文件中提取特定文本
【发布时间】:2020-02-11 02:08:19
【问题描述】:

我想使用 Regex 从文本文件中仅提取 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

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

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

但是 Input 给我带来了问题。我不知道如何使用文本文件作为输入。 而且,结果又不是很有说服力。

无论如何,任何人都可以帮助我以这种形式获得结果吗?

String IP1 = 192.168.0.1;
String IP2 = 192.168.0.2;

依此类推,直到文件中没有其他 192....

【问题讨论】:

  • 为了将来参考,请发布文本本身,而不是文本文件的图片。 (控制台中的文件和输出)
  • 这能回答你的问题吗? How to extract the IP of the string using RegEx
  • List&lt;string&gt; ipAddresses = File.ReadAllText(@"C:\Test\Result.txt").Split().Where(item =&gt; item.StartsWith("192.168")).ToList();

标签: c# regex text-files ip-address


【解决方案1】:

我认为这应该足够了:

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 行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多