Skip to Main Content
C# in a Nutshell, Second Edition
book

C# in a Nutshell, Second Edition

by Peter Drayton, Ben Albahari, Ted Neward
August 2003
Intermediate to advanced content levelIntermediate to advanced
928 pages
32h 1m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell, Second Edition

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# in a Nutshell

C# in a Nutshell

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

C# 7.0 in a Nutshell

Joseph Albahari, Ben Albahari
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
C# Cookbook

C# Cookbook

Joe Mayo

Publisher Resources

ISBN: 0596005261Catalog PageErrata