XML technologies / Regular expressions / .NET / Using regular expressions in .NET

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

Regular expressions in .NET are powerful, cleanly designed, and have a complete, easy-to-use interface. Microsoft did an excellent job with the implementation, but failed completely with the documentation. It is dreadful: incomplete, poorly written, unsystematically organized, and sometimes simply wrong. It took me a while to find my way around the package, and I hope this chapter makes .NET regular expressions a little clearer for you.

 

In brief: regular expressions in .NET

You can use the .NET regex package quite well without knowing the details of the regex class model. Those details matter for very specific information and efficiency questions, but the following sections present simple examples without explicitly creating classes. These are only examples; details follow later.

Every program using the regex package must import it with the line

Imports System.Text.RegularExpressions

at the start of the file (see Importing the regex namespace). The examples below assume this line is present.

All examples use the string variable TestStr. Here and throughout this chapter, user-chosen identifiers are printed in italics.

 

In brief: does the regex match?

The following example checks whether the regex matches the subject string:

If Regex.IsMatch(TestStr, "^\s*$")
    Console.WriteLine("Zeile ist leer.")
Else
    Console.WriteLine("Zeile ist nicht leer.")
End If

This example uses a matching option:

If Regex.IsMatch(TestStr, "^subject:", RegexOptions.IgnoreCase)
    Console.WriteLine("Die Zeile ist eine Betreffzeile.")
Else
    Console.WriteLine("Die Zeile ist keine Betreffzeile.")
End If

 

In brief: matching and matched text

The following examples examine the text found by the regex. If matching fails, the matched text DieZahl is set to the empty string:

Dim DieZahl as String = Regex.Match(TestStr, "\d+").Value
If DieZahl <> ""
    Console.WriteLine("Die Zahl lautet: " & DieZahl)
End If

This example uses a matching option:

Dim ImgTag as String = Regex.Match(TestStr, "<img\b[^>]*>", _
                                   RegexOptions.IgnoreCase).Value
If ImgTag <> ""
    Console.WriteLine("Image-Tag: " & ImgTag)
End If

 

In brief: matching with captured text

This example outputs the text from the first capturing group (that is, $1) as a string:

Dim Subject as String = _
    Regex.Match(TestStr, "^Subject: (.*)").Groups(1).Value
If Subject <> ""
    Console.WriteLine("Betreff: " & Subject)
End If

In C#, instead of Groups(1) you must use the square-bracket notation Groups[1].

Here is the same example with an option:

Dim Subject as String = _
    Regex.Match(TestStr, "^subject: (.*)", RegexOptions.IgnoreCase).Groups(1).Value
If Subject <> ""
    Console.WriteLine("Betreff: " & Subject)
End If

And the same again, this time with named capturing groups:

Dim Subject as String = _
    Regex.Match(TestStr, "^subject: (?<Subj>.*)", _
                RegexOptions.IgnoreCase).Groups("Subj").Value
If Subject <> ""
    Console.WriteLine("Betreff: " & Subject)
End If

 

In brief: search and replace

This example converts special HTML characters into HTML entities:

TestStr = Regex.Replace(TestStr, "&", "&amp;")
TestStr = Regex.Replace(TestStr, "<", "&lt;")
TestStr = Regex.Replace(TestStr, ">", "&gt;")
Console.WriteLine("Für HTML vorbereitet: " & TestStr)

The replacement text (the third argument) is interpreted specially, as explained in the box Special dollar sequences in replacement text. For example, in the replacement text, ›$&‹ is replaced by the matched text. The following example wraps words starting with capital letters in <B>...</B>:

TestStr = Regex.Replace(TestStr, "\b[A-Z]\w*", "<B>$&</B>")
Console.WriteLine("Veränderter String: " & TestStr)

This example replaces the sequence <B>...</B> (ignoring case) with <I>...</I>:

TestStr = Regex.Replace(TestStr, "<b>(.*?)</b>", "<I>$1</I>", RegexOptions.IgnoreCase)
Console.WriteLine("Veränderter String: " & TestStr)

  

  

 

 

 

German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.

O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln

back to top