XML technologies / Regular expressions / Features and dialects / Maintaining ⟦U+0003⟧ regular expressions / Procedural and object-oriented approaches

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

The procedural and object-oriented approaches share several features. In both, regex functionality is not built into the language, but implemented through ordinary functions (procedural) or constructors and methods (object-oriented). Operands are ordinary strings, interpreted as regular expressions by those functions, constructors, and methods.

The following examples use Java, VB.NET, PHP and Python.

 

Using regular expressions in Java

Consider the Java equivalent of the “Subject” example, using Sun's java.util.regex package. (Java is discussed thoroughly under Java.)

import java.util.regex.*; // Auf einfache Art alle Regex-Klassen einbinden. . . . Pattern r = Pattern.compile("^Subject: (.*)", Pattern.CASE_INSENSITIVE);     [= Schritt 1]
Matcher m = r.matcher(zeile);   [= Schritt 2]
if (m.find()) {                               [= Schritt 3]
 subject = m.group(1);                 [= Schritt 4]
}

Again, variable names are italic, regex-related elements bold, and the regex itself underlined. Strictly speaking, the underlined text is an ordinary literal string, later interpreted as a regex.

This illustrates the object-oriented approach, with regex functionality implemented in two classes from Sun's java.util.regex package: Pattern and Matcher. The steps are:

 

Step 1: Read and compile the regex into an internal, case-insensitive form, producing a Pattern object.

 

Step 2: Associate the subject text with the Pattern to produce a Matcher object.

 

Step 3: Apply the regex and check for a match.

 

Step 4: If successful, extract the first capturing group's text and store it in a variable.

Any regex program must perform these or similar steps. In Perl, many details are implicit; in this Java implementation, almost everything is explicit.

A procedural example

Sun's package also offers procedural functions that hide these details. Rather than creating regex objects and invoking their methods explicitly, they use temporary, single-use objects internally. Here is an example using Pattern.matches(...):

if (! Pattern.matches("\\s*", zeile))
{
    // ... Zeile ist nicht leer ...
}

This function implicitly wraps the regex in ˹^...$˼ and returns a boolean indicating success. Many packages, like Sun's, offer both interfaces. They differ in use (procedural interfaces are usually easier for simple tasks and harder for complex ones), functionality (usually less extensive procedurally), and efficiency (which often depends on the situation; see The art of writing regular expressions).

Sun has also integrated regex functionality elsewhere in the language. For example, the preceding example can use the String class's matches method:

if (! zeile.matches("\\s*", ))
{
    // ... Zeile ist nicht leer ...
}

This is less efficient than the explicit object-oriented form, so avoid it in a time-critical loop, but much more convenient for undemanding applications.

 

Regular expressions in VB and other .NET languages

Regex implementations do essentially the same work, but expose different amounts of it to programmers, even when sharing the same approach. Here is the “Subject” example in VB.NET (.NET is discussed thoroughly under .NET ):

Imports System.Text.RegularExpressions   ' Regex-Klassen einbinden.
    .
    . 
    .
Dim R as Regex = New Regex("^Subject: (.*)", RegexOptions.IgnoreCase)
Dim M as Match = R.Match(zeile)

If M.Success
    subject = M.Groups(1).Value
End If

This resembles the Java example, but .NET combines steps 1 and 3 into one, while step 4 also requires Value. Neither approach is better; their developers simply made the choices they thought appropriate at the time.

.NET also has procedural functions. This snippet tests for blank lines:

If Not Regex.IsMatch(Zeile, "^\s*$") Then
   ' ... Zeile ist nicht leer ...
End If

Unlike Sun's Pattern.matches function, which implies ˹^...$˼, Microsoft's function is more general: a convenient wrapper around regex objects. Programmers sacrifice little while saving typing and variable declarations.

Regular expressions in PHP

Here is the ˹Subject˼ example using PHP's procedural preg functions (PHP is discussed thoroughly under PHP ):

if (preg_match('/^Subject: (.*)/i', $zeile, $treffer))
      $subject = $treffer[1]

 

Regular expressions in Python

Finally, here is the “Subject” example in Python, which uses an object-oriented approach:

import re;
    .
    . 
    .
M = R.search(zeile)
if M:
    subject = M.group(1)

Again, it looks much like the preceding examples.

Why different approaches?

Why does each language do things differently? Some choices follow a language's structure and philosophy, but others reflect a package developer's preferences and skills. Java, for example, has several regex packages created by people seeking what Sun did not yet offer. Each has strengths and weaknesses and the same basic functionality, yet all differ from one another and from Sun's eventual built-in implementation.

PHP is another example of this variety: it contains three completely independent regex implementations. At different times, dissatisfied developers each added another package to the PHP core. The “preg” package is generally considered best, and is the only one discussed here.

  

 

 

 

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