How to replace multiple line breaks with one <BR>?

I replace all events \nwith a tag <BR>, but for some reason the text entered has a lot \nin the line, so I need to combine them.

Basically, if more than 1 \ n occur together, replace it with just one <BR> tag.

Can someone help me?

+5
source share
3 answers

This will replace any sequence of carriage returns ( \r) and / or linefeeds ( \n) with one <br />:

string formatted = Regex.Replace(original, @"[\r\n]+", "<br />");

, {2,} ( " " ) + ( " " "):

string formatted = Regex.Replace(original, @"[\r\n]{2,}", "<br />");

, CR + LF . , CR + LF , :

string formatted = Regex.Replace(original, @"(?:\r\n|\r(?!\n)|(?<!\r)\n){2,}", "<br />");
+18

:

str = Regex.Replace(str, @"[\r\n]+", "<br />");

Replace Regex, :

int oldLength;
do {
    oldLength = str.Length;
    str = str.Replace('\r', '\n');
    str = str.Replace("\n\n", "\n");
} while(str.Length != oldLength);

str = str.Replace("\n", "<br />");
+2

Note that string.Replace () is much faster than using RegEx:

string result = oldString.Replace("\n\n","\n");
result = result .Replace("\n","<br>");
-1
source

All Articles