Search code examples
c#contains

How to detect and delete a line in a text file containing a specific letter followed by random number?


I want specific lines in a text file, that contain the letter "p" followed by a random number to be detected and then completely deleted. Also: I do not know whether it is enough to let the program detect "p" directly followed by "0-9" (e.g. p3, p6) if the number after the "p" can differ from 0 to basically any number possible, for the program to detect the line and then delete it.

The text file looks like this:

randomline1
p123 = 123
p321 = 321
randomline2

After running the program, the text file should look like this:

randomline1
randomline2

I have tried to use the contains method but it says that there is an overload for said method, since there are 2 arguments (have a look at the code).

int[] anyNumber = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

foreach (string line in textfile)
{
    if (line.Contains("p{0}", anyNumber));
    {
        temp = line.Replace(line, "");
        newFile.Append(temp + "\r\n");
        continue;
    }

    newFile.Append(line + "\r\n");
}

The expected result should be, that the lines are detected and deleted, but instead an error message occurs: "No overload for method 'Contains' takes 2 arguments" (for the line containing the Contains method) and "Unreachable code detected" (attached to the last line) and "Possibly mistaken empty statement" (also for the line containing the Contains method).


Solution

  • @Antoine V has the right approach. You just need to change it to:

    Regex regex = new Regex(@"^p\d+");
    
    foreach (string line in textfile)
    {    
        if (!regex.IsMatch(line))
        {   
            // get only the lines without starting by pxxx
            newFile.Append(line + "\r\n");
        }
    }
    

    Now you append the line, only if it doesn't match the pattern. If it matches you do nothing. It doesn't align with your original code, where you add an empty line, but it aligns with your example.