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

Regular Expression Basics

Let’s start with simple expressions using the Regex and the Match classes.

Match m = Regex.Match("abracadabra", "(a|b|r)+");

This results in an instance of the Match class that can be tested for success without examining the contents of the matched string, as follows:

if (m.Success) {
  ...
}

To use the matched substring, simply convert it to a string:

Console.WriteLine("Match="+m.ToString( ));

The output of this example is the portion of the string that has been successfully matched, as follows:

Match=abra

Simple string replacements are also very straightforward. For example, consider the following statement:

string s = Regex.Replace("abracadabra", "abra", "zzzz");

This returns the string zzzzcadzzzz, in which all occurrences of the matching pattern are replaced by the replacement string zzzzz.

Now let’s look at a more complex expression:

string s = Regex.Replace("  abra  ", @"^\s*(.*?)\s*$", "$1");

This returns the string abra, with preceding and trailing spaces removed. This pattern is generally useful for removing leading and trailing spaces from any string. We could also have used the literal string quote construct in C#. Within a literal string, the compiler does not process the backslash character (\) as an escape character. Consequently, the @"..." is very useful when working with regular expressions, and when you are specifying escaped metacharacters with a \. Also of note is the use of $1 as the replacement string. The replacement string can contain only substitutions, ...

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