Search code examples
c#.netcarriage-returnlinefeed

Replace line feed (lf) with empty string without replacing lf in crlf C#


I wanted to replace any line feed (Lf) in a file with an empty string "". However, I don't want it to also replace the Lf in the CrLf one (end of line flag).

I was thinking something like this:

fileContent.Replace("\n","");

The line of code above will replace the Lf in CrLf to Cr, so I don't want that. Please give me some suggestion for a regular expression, which ignore the Lf in CrLf.

Thanks a lot.

PS: The logic changed. I used this:

fileContent = Regex.Replace(fileContent, @"\r\n(?=>)|(?<!\""\r)\n", ""); 

to replace all the CrLf that appear after > with empty string ("") and replace all the line feeds (Lf) that not followed by "Cr with empty string (""). Is that correct? Thanks


Solution

  • In addition to the other Regular Expression answer you can just use a Negative Look-Behind to avoid capturing the unnecessary data:

    string result = Regex.Replace(fileContent, @"(?<!\r)\n+", "");