1

I have some text like

This is a line




This is other line







This is another line

How to get rid of those multi empty lines ?

What I want is

This is a line

This is other line

This is another line

\s says that matches any whitespace character (spaces, tabs, line breaks) but I cannot figure out how to make multi empty line to just one empty line ?

Barış Velioğlu
  • 5,709
  • 15
  • 59
  • 105
  • possible duplicate of [Replacing multiple blank lines with one blank line using RegEx search and replace](http://stackoverflow.com/questions/4475042/replacing-multiple-blank-lines-with-one-blank-line-using-regex-search-and-replac) – Tim Schmelter Aug 31 '12 at 18:12

1 Answers1

5
Regex.Replace(input, @"(\r?\n\s*){2,}", Environment.NewLine + Environment.NewLine);

\r being optional lets it work with Unix-style line terminators. The output will have Windows-style terminators, though.

\s* allows it to match on lines that contain whitespace. (I had originally put in a ? here to make the match non-greedy, but that's not actually necessary and possibly detrimental in this case. In .NET regular expressions, \s and . don't match newlines with the default RegexOptions.)

{2,} makes sure it will only match with two successive newlines separated only by whitespace.

Sean U
  • 6,730
  • 1
  • 24
  • 43