XML technologies / Regular expressions / Extended introductory examples / Modifying text with regular expressions / Revisiting doubled words

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

The doubled-word problem from Introduction to regular expressions hopefully whetted your appetite for regex power. At this chapter's start, I also offered some wild code as its solution:

while (<>) {
  next if !s/\b([a-z]+)((?:\s|<[^>]+>)+)(\1\b)/\e[7m$1\e[m$2\e[7m$3\e[m/ig;
  s/^(?:[^\e]*\n)+//mg;         # Nicht markierte Zeilen löschen.
  s/^/$ARGV: /mg;               # Dateinamen voranstellen.
  print;
}

Now that you know some Perl, you should recognize the general structure: the <>, the three s/.../.../, and the print. It may still be confusing. If Perl and regexes are new to you, the following may be challenging.

Close up, these regexes are not so complex. First, clarify the problem and examine sample output:

% perl -w FindeDoppelt kap1.txt
kap1.txt: aufspürt. Solche Verdopplungen (wie »das das«) entstehen
kap1.txt: und Kleinschreibung wie bei ›Das das...‹ ignoriert,
kap1.txt: fett gedruckt hervorzuheben: '...das ist <B>sehr</B>
kap1.txt:     sehr wichtig...'.
kap1.txt: Ausdrücken denkt; sodass Sie sie anwenden
kap1.txt: sehr verschieden sein. Ein Programm kennt
kap1.txt: kennt vielleicht dieses oder jenes Zeichen nicht,
  .
  . 
  .

First the Perl program, then a version in Java with a different regex approach. Here I use s{Regex}{Ersatztext}Modifikatoren with braces, plus the /x modifier to comment the regex (also allowing the more readable ›next unless‹ instead of ›next if !‹). Otherwise, this is identical to the chapter's opening example.

Doubled words in Perl

$/ = ".\n";    # Ein spezieller Einlese-Modus; jede »Zeile« endet mit Punkt-Newline.

while (<>)   
{
    next unless s{              # (Regex beginnt hier.)
          ### Ein Wort erkennen:
          \b                    # Wortanfang ...
          ( [a-z]+ )            # Wort, setzt $1 (und \1).

          ### Whitespace und/oder <TAGS> dazwischen:
          (                     # Zwischenraum in $2 speichern.
              (?:               # (Dieses nicht-einfangende Klammerpaar gruppiert nur.)
                 \s                  # Whitespace (inkl. Newline, gut in diesem Fall)
                |                    # -oder-
                 <[^>]+>             # etwas wie <TAG>.
              )+                # Mindestens eins davon, aber auch mehr.
          )
      
          ### Und das gleiche Wort noch mal erkennen:
          (\1\b)                # \b, damit nicht Wortteile erkannt werden. Setzt $3.
                   
      # (Regex endet hier.)
    }
    # Ersatz-String folgt hier, mit den Modifikatoren /i, /g und /x.
    {\e[7m$1\e[m$2\e[7m$3\e[m}igx;  
      
    s/^(?:[^\e]*\n)+//mg;       # Nicht markierte Zeilen löschen.
    s/^/$ARGV: /mg;             # Jeder Zeile den Dateinamen voranstellen.
    print;
}

Some features are new. I explain them briefly, referring you to Perl documentation or, for regex details, Perl. Here, “magic” means a Perl feature you may not yet know.

 

Finally, print prints the remaining text, with filenames and escapes. The while loop repeats for every input paragraph, rather than individual lines.

Regexes with operators, functions, or objects

As noted at the start of Extended introductory examples, Perl illustrates concepts here. It works well, but other languages solve the problem easily too.

Perl makes demonstrations simpler because regexes are first-class language features, integrated as closely as numerical operators + and -, reducing surrounding machinery.

Most languages differ. As explained under Features and dialects, they provide functions and objects. A function might accept a regex string and a subject and return true on success. Usually compilation and matching are separate calls, as in this Java listing using java.util.regex, available since Java 1.4.

The same three regexes appear at the top as strings passed to Pattern.compile. Extra backslashes result from Java string syntax: each regex backslash needs escaping so Java's string parser leaves it intact.

 

Doubled words in Java

import java.io.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class TwoWord
{
 public static void main(String [] args)
 {
   Pattern regex1 = Pattern.compile(
       "\\b([a-z]+)((?:\\s|\\<[^>]+\\>)+)(\\1\\b)",
       Pattern.CASE_INSENSITIVE);
   String replace1 = "\033[7m$1\033[m$2\033[7m$3\033[m";
   Pattern regex2 = Pattern.compile("^(?:[^\\e]*\\n)+", Pattern.MULTILINE);
   Pattern regex3 = Pattern.compile("^([^\\n]+)", Pattern.MULTILINE);

   // Für alle auf der Befehlszeile angegebenen Argumente ...
   for (int i = 0; i < args.length; i++)
   {
     try {
       BufferedReader in = new BufferedReader(new FileReader(args[i]));
       String text;

       // Für jeden Abschnitt der Datei ...
       while ((text = getPara(in)) != null)
       {

           // Drei Substitutionen.
           text = regex1.matcher(text).replaceAll(replace1);
           text = regex2.matcher(text).replaceAll("");
           text = regex3.matcher(text).replaceAll(args[i] + ": $1");

           // Resultat ausgeben.
           System.out.print(text);
       }
     } catch (IOException e) {
       System.err.println("Kann Datei ["+args[i]+"] nicht lesen: " + e.getMessage());
     }
   }
 }

 // getPara liest den nächsten Abschnitt und gibt ihn als einen einzigen String zurück.
 static String getPara(BufferedReader in) throws java.io.IOException
 {
   StringBuffer buf = new StringBuffer();
   String line;
   
   while ((line = in.readLine()) != null &&
          (buf.length() == 0 || line.length() != 0))
   {
       buf.append(line + "\n");
   }
   return  buf.length() == 0 ? null : buf.toString();
 }
}

Regexes are initialized at the top, separately from use. The function Pattern.compile only analyzes and compiles them into internal forms, assigned to Pattern variables (regex1, etc.). Text processing applies these compiled forms through regex1.matcher(text) and replaces matched text. Details follow under Features and dialects. Every language requires two things: the regex dialect and the mechanism for using regexes in that language.

  

 

 

 

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