سؤال

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

هل كانت مفيدة؟

المحلول

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+", "");

نصائح أخرى

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");
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top