• Startseite
  • Tutorials
  • Kontakt
  • Mein Account
Panjutorials
  • Startseite
  • Tutorials
  • Kontakt
  • Mein Account

Regular expressions in CSharp

The following example uses a regular expression to search for repeated occurrences of words in a string. The regular expression \ b (? <Word> \ w +) \ s + (\ k <word>) \ b can be interpreted as shown in the following table.

Pattern Description
\b Start the match at a word boundary.
(?<word>\w+) Match one or more word characters up to a word boundary. Name this captured group word.
\s+ Match one or more white-space characters.
(\k<word>) Match the captured group that is named word.
\b Match a word boundary.

Note that the \ before word is not part of the code.

class Programm
    {


        public static void Main(string[] args)
        {
            // Define a regular expression that repeats and
            // ignores capitalization with ignoreCase
            Regex regex = new Regex(@"\b(?\<word\>\w+)\s+(\k\<word\>)\b",
              RegexOptions.Compiled | RegexOptions.IgnoreCase);

            // The teststring    
            string text = "This is a very very great text. I like it very much.";

            // Find occurences
            MatchCollection hits = regex.Matches(very);

            // Amount of occurences
            Console.WriteLine("{0} hit found at:\n   {1}",
                              hits.Count,
                              text);

            // Show the hits
            foreach (Match aHit in hits)
            {
                GroupCollection groups = aHit.Groups;
                Console.WriteLine("'{0}' repeated at position {1} and {2}",
                                  groups["word"].Value,
                                  groups[0].Index,
                                  groups[1].Index);
            }
            Console.ReadLine();
        }


    }

We can now use Regular Expressions to read all the possible patterns from a text and use them for our code. This could be done e.g.  to search your PC for repetitive files and display them to create some order and retain space.
For more details, I recommend the documentation.