-1

I am planning to write a c# program to check a test file for IP address strings and add them to a new test file line by line.

What is the best way to do this in c# ? (os should I use some other language)

Can someone share a code snippet that works.

Can regex handle this ? and cover all cases ?

or different files be handled on case by case basis.

The text file can be a email or even an IIS log file ?

Thanks in advance for the replies

Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
abmv
  • 7,042
  • 17
  • 62
  • 100
  • 1
    Possible duplicate of [Regular expression to match DNS hostname or IP Address?](http://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address) – Samvel Petrosov May 18 '17 at 06:43
  • sorry let me check if it is helpfull – abmv May 18 '17 at 06:54

1 Answers1

2

You could do this in many different languages. Regular expressions in C# would work just fine for this. There are many ways to do it, depending on a number of factors such as input file size. A simple way would be to read all lines of the source file, iterate over each line using a regular expression to identify a match, and if matched, write the line to a target file.

Something like this could be a starting point.

public static string Foo()
{
    // see http://stackoverflow.com/questions/4890789/regex-for-an-ip-address
    Regex ip = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");

    string[] inputLines = File.ReadAllLines("sourcefile.txt");
    List<string> outputLines = new List<string>();

    foreach (string line in inputLines)
    {
        MatchCollection result = ip.Matches(line);
        if (result[0].Success) outputLines.Add(line);
    }

    if (outputLines.Count > 0)
    {
        File.AppendAllLines("destinationfile.txt", outputLines);
    }
}
joelc
  • 2,687
  • 5
  • 40
  • 60