C# 从文件中删除以特定单词开头的行

C# removing a line from file that starts with a specific word

在 C# 中,从文件中删除以特定单词开头的行的高效而优雅的方法是什么?我知道如何删除一行中任何位置包含特定单词的行,但我无法删除以特定单词开头的行。谢谢!

首先,我们应该定义“以特定的单词开头”的含义。

  • 如果word只是一个子串,那么string.StartsWith就够了;
  • 如果单词是后续字母,那么我们可以尝试正则表达式:

代码。子字符串大小写:

 using System.IO;
 using System.Linq;

 ...

 string fileName = @"c:\myFile.txt";

 File.WriteAllLines(fileName, File
   .ReadLines(fileName)
   .Where(line => !line.StartsWith(myWord))
   .ToArray());

正则表达式大小写:

 using System.IO;
 using System.Linq;
 using System.Text.RegularExpressions;

 ...

 string fileName = @"c:\myFile.txt";

 Regex regex = new Regex($@"^{Regex.Escape(myWord)}\b");

 File.WriteAllLines(fileName, File
   .ReadLines(fileName)
   .Where(line => !regex.IsMatch(line))
   .ToArray());