How can I replace multiple line breaks with a single <BR>?
I am replaci开发者_Go百科ng all occurances of \n
with the <BR>
tag, but for some reason the text entered has many \n
in a row, so I need to combine them.
Basically, if more than 1 \n occur together, replace it with just a single <BR> tag.
Can someone help me with this?
This will replace any sequence of carriage-returns (\r
) and/or linefeeds (\n
) with a single <br />
:
string formatted = Regex.Replace(original, @"[\r\n]+", "<br />");
If you only want to replace sequences of two or more items then the simplistic answer is to use the {2,}
quantifier (which means "at least two repetitions") instead of +
(which means "at least one repetition"):
string formatted = Regex.Replace(original, @"[\r\n]{2,}", "<br />");
Note that the expression above will treat the common CR+LF combination as a sequence of two items. It's probable that you'll want to treat CR+LF as a single item instead, in which case the expression becomes slightly more complicated:
string formatted = Regex.Replace(original, @"(?:\r\n|\r(?!\n)|(?<!\r)\n){2,}", "<br />");
Use the following code:
str = Regex.Replace(str, @"[\r\n]+", "<br />");
It could well be faster to call the normal Replace
method multiple times and not use a Regex at all, like this:
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 />");
Note that string.Replace() is much faster than using RegEx:
string result = oldString.Replace("\n\n","\n");
result = result .Replace("\n","<br>");
精彩评论