XML technologies / Regular expressions / Features and dialects / Maintaining and ⟦U+0003⟧ caring for regular expressions / Examples using “search and replace”

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

The “Subject” example is very simple, so the differences between approaches are barely apparent. This section examines a slightly larger example, giving the implementations a chance to reveal their differences.

In Converting plain text to HTML: putting it together we used the following Perl fragment to turn email addresses into “mailto:” links using search and replace:

$text =~ s{
   \b
   # Adresse in $1 abspeichern ...
   (
     \w[-.\w]*                          # Username
     @
     [-\w]+(\.[-\w]+)*\.(com|edu|info)  # Hostname
   )
   \b
}{<a href="mailto:$1">$1</a>}gix;

Perl’s search-and-replace operator modifies the subject string directly: replacement changes the contents of the subject-string variable. In most other languages, replacement operates on a copy of the subject string.

This is useful if the original subject string is needed again, but requires another assignment to continue using the same variable with modified contents. Examples follow.

   

Search and replace in Java

Here is the same example in Java using Sun’s java.util.regex package:

import java.util.regex.*; // Alle Regex-Klassen einbinden.
    .
    . 
    .
Pattern r = Pattern.compile(
   "\\b                                                             \n"+
   "#  Adresse in $1 abspeichern ...                                \n"+
   "(                                                               \n"+
   "  \\w[-.\\w]*                                 # Username        \n"+
   "  @                                                             \n"+
   "  [-\\w]+(\\.[-\\w]+)*\\.(com|edu|info)       # Hostname        \n"+
   ")                                                               \n"+
   "\\b                                                             \n",
   Pattern.CASE_INSENSITIVE|Pattern.COMMENTS);

Matcher m = r.matcher(text);
text = m.replaceAll("<a href=\"mailto:$(1)\">$(1)</a>");

Notice that each backslash ›\‹ in the regex appears in the string as ›\\‹. Thus ›\\w‹ in the literal string becomes ›\w‹ in the regular expression. For debugging, printing the regex with

System.out.println(r.pattern())

can help: it shows the regex as received by the regex functions.

Appropriate flags also allow comments in Java regular expressions. These extend from the comment character ›#‹ to the next newline. Some newlines in the expression above are therefore essential.

Perl uses modifiers such as /g, /i and /x for special options (global matching, ignoring case, free-form); in java.util.regex either a special function is used (replaceAll statt replace) or options are passed as function arguments (here Pattern.CASE_INSENSITIVE and Pattern.COMMENTS).

 

Search and replace in VB.NET

In VB.NET this again looks very similar:

Dim R As Regex = New Regex _
("\b                                                       " & _
 "(?# Adresse in $1 abspeichern ...)                       " & _
 "(                                                        " & _
 "  \w[-.\w]*                           (?# Username )     " & _
 "  @                                                      " & _
 "  [-\w]+(\.[-\w]+)*\.(com|edu|info)   (?# Hostname )     " & _
 ")                                                        " & _
 "\b                                                       ",  _
 RegexOptions.IgnoreCase Or RegexOptions.IgnorePatternWhitespace)

text = R.Replace(text, "<a href=""mailto:${1}"">${1}</a>")

Because VB.NET string literals are rather inflexible (they cannot span multiple lines, and inserting a newline is difficult), handling longer regular expressions is less pleasant than in other languages. On the other hand, precisely because ›\‹ is not a string metacharacter in VB.NET, regex backslashes need not be doubled. The quotation mark ›"‹ is a string metacharacter in VB.NET: to include a quotation mark in a string, it must be entered twice.

 

Search and replace in PHP

Here is the same example in PHP:

$text = preg_replace(fl{
                         \b
                         # Adresse in $1 abspeichern...
                         (
                           \w[-.\w]*                          # Username
                           @
                           [-\w]+(\.[-\w]+)*\.(com|edu|info)  # Hostname
                         )
                         \b
                     }ixfl,
                     fl<a href="mailto:$1">$1</a>',           # Ersatztext
                     $text);

As in Java and VB.NET, the search-and-replace result must be assigned back to the string variable $text , but otherwise this code closely resembles the Perl example.

  

 

 

 

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