简体   繁体   中英

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

What is an efficient and elegant way to remove a line from a file that starts with a specific word in C#? I know how to remove a line if it contains a specific word anywhere in the line, but I am having trouble removing a line that starts with a specific word. Thanks!

First, we should define what "starts with a specific word " means.

  • If word is just a substring , then string.StartsWith is enough;
  • If word is consequent letters, then we can try regular expressions :

Code. Substring case:

 using System.IO;
 using System.Linq;

 ...

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

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

Regular expressions case:

 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());

 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM