Quickly Clean-up Blank lines from a multi-line String


Scenario : At the time of consuming data from another application or program, one of the frequent issue is data in and data out ! I was working for similar scenario the other day where a flat was generated and then another program had lexical parser and would generate tokens etc. Long story short, in a typical workflow we had blank lines and they were causing issue. Very simple issue … once this stupid thing is identified and verified being the actual culprit !

Let’s take a look :

using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      string s = @"a
a
aa

aaa




aaaa

";
    var ss = Regex.Replace(s, @"^\s+$[\r\n]*", "", RegexOptions.Multiline)
      .TrimEnd()
      ;
    Console.WriteLine("---x--o--x--");
    Console.WriteLine("From :");
    Console.WriteLine("---x--o--x--");
    Console.WriteLine(s);
    Console.WriteLine("---x--o--x--");
    Console.WriteLine("To :");
    Console.WriteLine("---x--o--x--");
    Console.WriteLine(ss);
    Console.WriteLine("---x--o--x--");
    }
  }
}

Output :

—x–o–x–
From :
—x–o–x–
a
a
aa

aaa

aaaa

—x–o–x–
To :
—x–o–x–
a
a
aa
aaa
aaaa
—x–o–x–

Advertisements

Published by

Aarsh Talati

Software Developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s