XML technologies / Regular expressions / .NET / Objects in detail / regex objects: creation

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

The constructor for Regex objects is simple. The first argument is the regex as a string; the optional second argument supplies options. Here is a one-argument example:

Dim StripTrailWS = new Regex("\s+$") ' Whitespace am Ende entfernen.

This merely creates a Regex object and prepares it for use; no search occurs yet.

A two-argument example looks like this:

Dim GetSubject = new Regex("^subject: (.*)", RegexOptions.IgnoreCase)

Using OR allows multiple options:

Dim GetSubject = new Regex("^subject: (.*)", _
                           RegexOptions.IgnoreCase OR RegexOptions.Multiline)

 

Catching exceptions

A syntactically invalid regex throws ArgumentException . Usually this is not caught for a self-developed regex embedded in the program. But validating regexes from outside sources, such as configuration files or user input, is very important. For example:

Dim R As Regex
Try
    R = New Regex(BenutzerEingabe)
Catch e As ArgumentException
    Console.WriteLine("*ERROR* Fehler in der Regex: " & e.ToString)
    Exit Sub
End Try

Depending on the situation, merely printing the error may not suffice.

 

Regex options

The constructor for a Regex object accepts these options:

 

RegexOptions.IgnoreCase

This option ignores case in the subject string (see Case-insensitive mode).

 

RegexOptions.IgnorePatternWhitespace

This option parses the regex in free-spacing mode (see Free-spacing mode). Comments are also allowed. With bare comments starting with ˹#...˼, a newline must end the comment; otherwise, the rest of the regex is commented out.

In VB.NET, this requires chr(10), as in this example:

Dim R as Regex = New Regex( _
    "# Eine Fließkommazahl ...                     " & chr(10) & _
    "  \d+(?:\.\d*)? # Ziffern am Anfang ...       " & chr(10) & _
    "  |             # ... oder ...                " & chr(10) & _
    "  \.\d+         # ... nur ein Dezimalpunkt    ", _
    RegexOptions.IgnorePatternWhitespace)

This is cumbersome. In VB.NET, the parenthesized comment form ˹(?#...)˼ is much more practical:

Dim R as Regex = New Regex( _
    "(?# Eine Fließkommazahl ...                      )" & _
    "  \d+(?:\.\d*)? (?# Ziffern am Anfang ...        )" & _
    "  |             (?# ... oder ...                 )" & _
    "  \.\d+         (?# ... nur ein Dezimalpunkt     )", _
    RegexOptions.IgnorePatternWhitespace)

 

RegexOptions.Multiline

The regex is applied in enhanced-line-anchor or multiline mode (see Enhanced-line-anchor or multiline mode). The metacharacters ˹^˼ and ˹$˼ also match at newlines within the string, not just at its beginning or end.

 

RegexOptions.Singleline

This option changes ›.‹ so dot truly matches every character (see Dot-matches-all mode); normally, newline is excluded.

 

RegexOptions.ExplicitCapture

This option makes ordinary parentheses ˹(...)˼, normally capturing text, into noncapturing groups. They behave like ˹(?:...)˼ and only group. Named groups ˹(?<Name>...)˼ can still capture text.

If you already use named groups alongside groups that should capture nothing, this option makes the regex much more readable.

 

RegexOptions.RightToLeft

This option enables right-to-left mode (see Right-to-left matching).

 

RegexOptions.Compiled

This option compiles the regex into a more optimized format, usually making matching much faster. Initial compilation takes much longer, however, and the program uses more memory throughout its lifetime.

If a regex is used only once or rarely, RegexOptions.Compiled is not very useful: the extra memory is not released as it would be for an ordinary Regex object after use. Repeated usage in time-critical code generally makes this option worthwhile.

An example appears in Benchmarking with VB.NET, where it halves the runtime. Also consider compiling a regex into an assembly (see Regex assemblies).

 

RegexOptions.ECMAScript

This option parses the regex as ECMAScript would (see ECMAScript mode). If you do not know ECMAScript and need no compatibility with it, you may safely ignore this option.

 

RegexOptions.None

This non-option simply initializes a variable of type RegexOptions . Additional options may be added later with OR .

  

 

 

 

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