如何检测和删除包含特定字母后跟随机数的文本文件中的一行?

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

我想检测文本文件中包含字母 "p" 后跟随机数的特定行,然后将其完全删除。 另外:我不知道如果 "p" 后面的数字可以从 0 到基本上不同,让程序检测直接跟在“0-9”(例如 p3,p6)之后是否足够任何可能的数字,以便程序检测该行然后将其删除。

文本文件如下所示:

randomline1
p123 = 123
p321 = 321
randomline2

在 运行 程序之后,文本文件应该如下所示:

randomline1
randomline2

我尝试使用 contains 方法,但它说该方法有一个重载,因为有 2 个参数(查看代码)。

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

预期的结果应该是检测到并删除了行,但出现了一条错误消息:"No overload for method 'Contains' takes 2 arguments"(对于包含 Contains 方法的行)和 "Unreachable code detected" (附加到最后一行)和 "Possibly mistaken empty statement"(也用于包含 Contains 方法的行)。

如果需要匹配多个数字,请使用d+。然后您添加字母 p 进行过滤。最后,使用 ^ 只匹配以 pxxx

开头的行
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(temp + "\r\n");
   }
   newFile.Append(line + "\r\n");
}

@Antoine V 有正确的方法。您只需要将其更改为:

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

现在您追加该行,仅当它与模式不匹配时。如果它匹配你什么也不做。它与您添加空行的原始代码不一致,但与您的示例一致。