简体   繁体   中英

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

除了其他Regular Expression答案外,您还可以使用负向后看来避免捕获不必要的数据:

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

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