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



我希望文本文件中的特定行,其中包含字母"p",后跟一个随机数,然后被检测,然后完全删除。 另外:我不知道让程序检测"p"后面紧跟着"0-9"(例如 p3、p6)是否足够,如果"p"后面的数字可以从 0 到基本上任何可能的数字,让程序检测该行然后删除它。

文本文件如下所示:

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 + "rn");
continue;
}
newFile.Append(line + "rn");
}

预期结果应该是,检测到并删除了这些行,但会出现一条错误消息:"方法'Contains'没有重载需要 2 个参数"(对于包含Contains方法的行)和"检测到无法访问的代码"(附加到最后一行)和"可能错误的空语句"(也适用于包含Contains方法的行)。

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

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

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

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

现在,仅当该行与模式不匹配时,才附加该行。如果匹配,则不执行任何操作。它与添加空行的原始代码不一致,但它与您的示例一致。

最新更新