0

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

Steven
  • 3
  • 3

2 Answers2

3

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+", "");
Jason Larke
  • 5,289
  • 25
  • 28
  • 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 – Steven Aug 01 '12 at 13:28
  • @Steven No that probably won't work. Try this `@"(?<=>)(?:\r\n)+|(?<!\r)\n+"` – Jason Larke Aug 02 '12 at 00:54
2

You could use a regular expression. The RegEx below matches \n characters that are either at the beginning of the input or are preceded with \r. It captures the character preceding the \n in a group so it can re-insert it into the string.

string result = Regex.Replace(fileContent, @"(^|[^\r])\n", "$1");
Glen Hughes
  • 4,712
  • 2
  • 20
  • 25