C Sharp find blank lines

From Regex Regular Expression Encyclopedia

Jump to: navigation, search

You can use this recipe for identifying blank lines in a file. Blank lines can contain spaces or tabs, or they can contain a combination of spaces and tabs. Variations on these expressions can be useful for stripping blank lines from a file.

[edit] code

using System;
using System.IO;
using System.Text.RegularExpressions;
public class Recipe
{
    private static Regex _Regex = new Regex( @"^\s*$" );
    public void Run(string fileName)
    {
        String line;
        int lineNbr = 0;
        using (StreamReader sr = new StreamReader(fileName))
        {
            while(null != (line = sr.ReadLine()))
            {
                lineNbr++;
                if (_Regex.IsMatch(line))
                {
                  Console.WriteLine("Found match '{0}' at line {1}",
                      line,
                      lineNbr);
              }
 
          }
      }
  }
  public static void Main( string[] args )
  {
      Recipe r = new Recipe();
      r.Run(args[0]);
  }
}

[edit] How It Works

In addition to completely blank lines, this expression also matches lines that have only tabs or spaces in them. It does this by using the \s character class, which matches a tab or a space.

    Here's the expression broken down into parts:
Regular Expression Description
^ starts the beginning of the line, followed by . . .
\s any whitespace character (a tab or space) . . .
* zero or more times, followed by . . .
$ the end of the line.
Personal tools