XML technologies / Regular expressions / .NET / Advanced regular expressions in .NET / regex assemblies

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

In .NET, Regex objects can be packaged into assemblies, storing regex libraries as DLLs. The following box shows how.

 

Creating custom regex libraries with assemblies

This example creates a small regex library, an assembly or DLL, containing three predefined Regex constructors named jfriedl.Mail.Subject, jfriedl.Mail.From and jfriedl.CSV.GetField.

The first two are simple examples illustrating the basic process. The third is complex enough to justify its own library. Note that option RegexOptions.Compiled is not specified: creating an assembly implies it. The main text below explains how to use the library.

Option Explicit On
Option Strict On

Imports System.Text.RegularExpressions
Imports System.Reflection

Module BibliothekErzeugen
Sub Main()
 'Argumente bei den Aufrufen von RegexCompilationInfo: Regex, Optionen, Name innerhalb
 'der Klasse, Name der Klasse und ein boolescher Wert, der besagt, ob die Klasse »public« ist.
 'Programme benutzen die erste Klasse mit »jfriedl.Mail.Subject«, einem Konstruktor.
 Dim RCInfo() as RegexCompilationInfo = {                                           _
New RegexCompilationInfo(                                                        _
  "^Subject:\s*(.*)", RegexOptions.IgnoreCase, "Subject", "jfriedl.Mail", true), _
New RegexCompilationInfo(                                                        _
  "^From:\s*(.*)", RegexOptions.IgnoreCase, "From", "jfriedl.Mail", true),       _
New RegexCompilationInfo(                                                        _
  "\G(?:^|,)                                                             " &     _
  "(?:                                                                   " &     _
  "    (?# Entweder ein Feld in Anführungszeichen ... )                  " &     _
  "    ""  (?# Öffnendes Anführungszeichen )                             " &     _
  "     (?<QuotedField>  (?> [^""]+ | """" )*   )                        " &     _
  "    ""  (?# Schließendes Anführungszeichen )                          " &     _
  "  (?# ... oder ... )                                                  " &     _
  "  |                                                                   " &     _
  "    (?# ... ein ’nacktes’ Feld ohne Kommas und Anführungszeichen. )   " &     _
  "    (?<UnquotedField> [^"",]* )                                       " &     _
  ")",                                                                           _
  RegexOptions.IgnorePatternWhitespace, "GetField", "jfriedl.CSV", true)         _
 }
 'Jetzt nehmen wir den ganzen Brocken und schreiben die Bibliothek auf Festplatte ...
 Dim AN as AssemblyName = new AssemblyName()
 AN.Name = "JfriedlsRegexLibrary"      'Dateiname der DLL.
 AN.Version = New Version("1.0.0.0")
 Regex.CompileToAssembly(RCInfo, AN)   'Bibliothek und DLL erzeugen.
End Sub
End Module

Running the boxed program creates an assembly and saves it in library JfriedlsRegexLibrary.DLL in the project’s bin directory.

Other projects can use this assembly by adding it to the current Visual Studio project using menu option Project > Add Reference.

First import the assembly’s classes:

Imports jfriedl

Then use them like any other class, as in this example:

Dim FeldRegex as CSV.GetField = New CSV.GetField 'Neues Regex-Objekt erzeugen.
   ...
Dim FeldMatch as Match = FeldRegex.Match(Zeile) 'Regex auf einen String anwenden.
While FeldMatch.Success
  Dim Feld as String
  If FeldMatch.Groups(1).Success
    Feld = FeldMatch.Groups("QuotedField").Value
    Feld = Regex.Replace(Feld, """""", """") 'Verdoppelte Anführungszeichen -> einfache.
  Else
    Feld = FeldMatch.Groups("UnquotedField").Value
  End If
Console.WriteLine("[" & Feld & "]")
  ' Wert in Feld kann jetzt weiterverarbeitet werden.
  FeldMatch = FeldMatch.NextMatch
End While

This example imports only the namespace jfriedl , but could instead specify namespace jfriedl.CSV in the Imports statement. The Regex object would then be created as follows:

Dim FeldRegex as GetField = New GetField 'Regex-Objekt erzeugen.

The difference is mostly stylistic. You need not import anything: every class can be fully qualified:

Dim FeldRegex as jfriedl.CSV.GetField = New jfriedl.CSV.GetField

This is somewhat cumbersome but identifies the object’s origin precisely. Again, it is a matter of style.

  

 

 

 

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