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

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

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