O'Reilly logo

C# in a Nutshell by Peter Drayton, Ted Neward, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Procedural- and Expression-Based Patterns

Generally, users of regular expressions fall into one of two groups. The first group tends to use minimal regular expressions that provide matching or grouping behaviors, and then write procedural code to perform some iterative behavior. The second group tries to utilize the maximum power and functionality of the expression-processing engine itself, with as little procedural logic as possible. For most of us, the best answer is somewhere in-between. We’ll now explore the trade-offs in complexity and performance of these two approaches.

Procedural-Based Patterns

A common processing need is to match certain parts of a string and perform some processing. So, here’s an example that matches words within a string and capitalizes them:

using System;
using System.Text.RegularExpressions;
  
class ProceduralFun {
  static void Main() {
    string txt = "the quick red fox jumped over the lazy brown dog.";
    Console.WriteLine("text=["+txt+"]");
    string res = "";
    string pat = @"\w+|\W+";
  
    // Loop through all the matches
    foreach (Match m in Regex.Matches(txt, pat)) {
      string s = m.ToString();
  
      // If the first char is lower case, capitalize it
      if (char.IsLower(s[0]))
        s = char.ToUpper(s[0])+s.Substring(1, s.Length-1); 
      res += s; // Collect the text
    }
    Console.WriteLine("result=["+res+"]");
  }
}

As you can see, you use the C# foreach statement to process the set of matches found, and perform some processing (in this case, creating a new result string).

The output of the sample ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required