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