Search code examples
c#regextext-filesip-address

Extract Specific Text from a Text File Using C#


I want to extract Only IP Addresses from a text file using Regex.

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

For example, in this picture, I want only IP addresses that match with this string, 192.168. and so on. and would like to save each match in a separate variable.

            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());

I tried this Code but the results are not very convincing.

CMD Results

Also as we can see that this chunk of code is not providing all matches.

I have also tried this code

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

But the Input is causing the issue for me. I don't know how to use a Text file as an Input. also, the result is not very convincing again.

Anyways, anybody can help me to get the result in this form?

String IP1 = 192.168.0.1;
String IP2 = 192.168.0.2;

and so on until there is no other 192.... in the file also it would be great if we skip the first 3 lines while reading as they are useless in my scenario.


Solution

  • I think this should be sufficent:

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

    It only extracts ip addressess that start with 192.168 and skips 3 first lines.