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.
string.StartsWith
is enough;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.