C Sharp Search for Lines Beginning with a Word

From Regex Regular Expression Encyclopedia

Jump to: navigation, search

This recipe allows you to find whole words at the beginning of a line.

[edit] code

using System;
using System.IO;
using System.Text.RegularExpressions;
public class Recipe
{
    private static Regex _Regex = new Regex( @"^Moo\b" );
    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

The key to this expression is the line anchor metacharacter ^. You can break the expression down like this:

Regular Expression Description
^ at the start of the line, followed immediately by . . .
W then . . .
o followed by . . .
r then . . .
d and lastly . . .
\b a word boundary.

The \b character class is an anchor like the ^ line anchor. However, \b is a word anchor, and the ^ metacharacter is a line anchor.

Personal tools