C Sharp Search for Repeated Words

From Regex Regular Expression Encyclopedia

Jump to: navigation, search

You can use this recipe to find words that appear more than once on a line, such as the the.

[edit] code

using System;
using System.IO;
using System.Text.RegularExpressions;
public class Recipe
{
    private static Regex _Regex = new Regex( @"\b(\w+)\s\1\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 most important aspect of this regular expression is the back reference, which is \1 in all the previous recipes. The back reference is just a way of saying “whatever you found in the first group.” The parentheses in the expression define the group. Here’s a breakdown of the expression:

Regular Expression Description
\b is a word boundary, followed by . . .
(...) a group (explained next), then . . .
\s a space . . .
+ one or more times, then . . .
\1 whatever was found in the group, and lastly . . .
\b a word boundary.
The group is simply (\w+), which is as follows:
\w a word character . . .
+ found one or more times.

This will match a word. The expression begins and ends with a word boundary anchor. This is to prevent the expression from matching a string such as quarterback backrub. If the word boundary anchors are removed, the expression will start matching subsections of words.

Personal tools