Skip to Main Content
C# in a Nutshell
book

C# in a Nutshell

by Ben Albahari, Ted Neward, Peter Drayton
March 2002
Intermediate to advanced content levelIntermediate to advanced
864 pages
31h 8m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# 8.0 in a Nutshell

C# 8.0 in a Nutshell

Joseph Albahari, Eric Johannsen
C# 10 in a Nutshell

C# 10 in a Nutshell

Joseph Albahari
C# in a Nutshell, Second Edition

C# in a Nutshell, Second Edition

Peter Drayton, Ben Albahari, Ted Neward
Code like a Pro in C#

Code like a Pro in C#

Jort Rodenburg

Publisher Resources

ISBN: 0596001819Catalog PageErrata