Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace multiple line breaks with a single <BR>?

Tags:

c#

regex

editor

I am replacing 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?

like image 898
mrblah Avatar asked Nov 12 '09 22:11

mrblah


People also ask

How do you remove break lines from a string?

Use the String. replace() method to remove all line breaks from a string, e.g. str. replace(/[\r\n]/gm, ''); . The replace() method will remove all line breaks from the string by replacing them with an empty string.

How do you replace a new line character in Java?

Line Break: A line break (“\n”) is a single character that defines the line change. In order to replace all line breaks from strings replace() function can be used.


2 Answers

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 />");
like image 138
LukeH Avatar answered Sep 19 '22 07:09

LukeH


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 />");
like image 32
SLaks Avatar answered Sep 20 '22 07:09

SLaks