XML technologies / Regular expressions / Java / More programming examples

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

 

Adding WIDTH and HEIGHT attributes to HTML IMG tags

This section presents a more complex version of Searching and replacing. In HTML text represented by a StringBuilder, StringBuffer, or another mutable CharSequence, we want to ensure that every image, every IMG tag, explicitly specifies WIDTH and HEIGHT.

Without these attributes, the browser cannot know how much space to reserve for images. Page construction appears slow, jumpy, or both, since each image must be downloaded and measured before being positioned. If HTML specifies image dimensions, however, the browser can immediately lay out the text and load images later without changing the layout. The page looks finished from the outset. (Note: At Yahoo!, the mantra has been “For IMG, always WIDTH and HEIGHT!” since the early web. Yet many professionally produced pages still omit image dimensions.)

On finding an IMG tag, the program searches it for SRC, WIDTH, and HEIGHT attributes and extracts any values present. If an attribute is missing, it downloads the image from the server, measures its height and width, and builds WIDTH and HEIGHT attributes from those data.

If both WIDTH and HEIGHT are missing, the actual image dimensions are inserted. If only one is present, the other is calculated to preserve the aspect ratio, scaling the image. For example, if WIDTH specifies half the actual width, HEIGHT also receives half the actual height. Current browsers behave this way too.

Like the example under Direct searching and replacing, this maintains an explicit pointer to the current position. We use regions (see The matcher’s region) and Method chaining:

// Matcher zum Herauslösen von <IMG>-Tags.
Matcher mImg    = Pattern.compile("(?id)<IMG\\s+(.*?)/?>").matcher(html);

// Matcher für die SRC-, WIDTH- und HEIGHT-Attribute innerhalb eines Tags.
Matcher mSrc    = Pattern.compile("(?ix)\\bSRC   =(\\S+)").matcher(html);
Matcher mWidth  = Pattern.compile("(?ix)\\bWIDTH =(\\S+)").matcher(html);
Matcher mHeight = Pattern.compile("(?ix)\\bHEIGHT=(\\S+)").matcher(html);

// Die erste Suche beginnt am Anfang des Strings.
int imgMatchZeiger = 0;
while (mImg.find(imgMatchZeiger)) {
   imgMatchZeiger = mImg.end(); // Vom Ende des letzten <IMG>-Tags aus weitersuchen.

  // Attribute innerhalb des eben gefundenen <IMG>-Tags suchen.
   Boolean hatSrc    =    mSrc.region( mImg.start(1), mImg.end(1) ).find();
   Boolean hatHeight = mHeight.region( mImg.start(1), mImg.end(1) ).find();
   Boolean hatWidth  =  mWidth.region( mImg.start(1), mImg.end(1) ).find();

  // SRC-Attribut gefunden, aber kein WIDTH- und/oder kein HEIGHT-Attribut ...
   if (hatSrc && (! hatWidth || ! hatHeight)) {

     java.awt.image.BufferedImage i = // Bild herunterladen.
         javax.imageio.ImageIO.read(new java.net.URL(mSrc.group(1)));

     String size; // Für die fehlenden WIDTH- und/oder HEIGHT-Attribute.
      if (hatWidth)
          // Breite vorhanden, Höhe unter Einhaltung des Seitenverhältnisses berechnen.
          size = "height='" + (int)(Integer.parseInt(mWidth.group(1)) *
                                     i.getHeight() / i.getWidth())  + "' ";
      else if (hatHeight)
          // Höhe vorhanden, Breite unter Einhaltung des Seitenverhältnisses berechnen.
          size = "width='"  + (int)(Integer.parseInt(mHeight.group(1)) *
                                    i.getWidth()  / i.getHeight()) + "' ";
      else // Weder Höhe noch Breite vorhanden; die wahren Dimensionen des Bilds einsetzen.
          size = "width='"  + i.getWidth()  + "' " +
                 "height='" + i.getHeight() + "' ";

      html.insert(mImg.start(1), size); // Attribute einfügen.
      imgMatchZeiger += size.length();  // Um die Anzahl der neuen Zeichen weiterschalten.
   }
}

The example is instructive but has several shortcomings. Focusing on searching and replacing, I assumed that the HTML string satisfied certain conditions. For example, the attribute regexes allow neither whitespace around the equals sign nor double-quoted values. The Perl example under Matching an HTML link contains regexes handling that syntax correctly. The program also cannot handle relative or malformed URLs, and it does not catch exceptions raised while downloading images.

Nevertheless, the example illustrates several valuable concepts.

 

One matcher with several patterns for checking HTML

This is the Java version of the Perl program that checks a string against a subset of HTML. It uses the usePattern method to apply several regexes in one matcher. These regexes all begin with ˹\G˼ and work through the text together as an HTML tag team. The box An example of using \G in Perl explains how the team works.

Pattern pAmEnde   = Pattern.compile("\\G\\z");
Pattern pWort     = Pattern.compile("\\G\\w+");
Pattern pKeinHtml = Pattern.compile("\\G[^\\w<>&]+");
Pattern pImgTag   = Pattern.compile("\\G(?i)<img\\s+([^>]+)>");
Pattern pLink     = Pattern.compile("\\G(?i)<A\\s+([^>]+)>");
Pattern pLinkX    = Pattern.compile("\\G(?i)</A>");
Pattern pEntity   = Pattern.compile("\\G&(#\\d+|\\w+);");

boolean needClose = false;
Matcher m = pAmEnde.matcher(html); // Den Matcher können wir mit jedem Pattern erzeugen.

while (! m.usePattern(pAmEnde).find())
{
   if (m.usePattern(pWort).find()) {
      // Ein Wort oder eine Zahl in m.group() -- auf Obszönitäten usw. prüfen ...
   } else if (m.usePattern(pImgTag).find()) {
      // Ein IMG-Tag -- Inhalt auf Zulässigkeit prüfen ...
   } else if (! needClose && m.usePattern(pLink).find()) {
      // Ein Link -- den wir hier überprüfen können ...
      needClose = true;
   } else if (needClose && m.usePattern(pLinkX).find()) {
      System.out.println("/LINK [" + m.group() + "]");
      needClose = false;
   } else if (m.usePattern(pEntity).find()) {
      // Entities wie &gt; oder &#123; zulassen.
   } else if (m.usePattern(pKeinHtml).find()) {
      // Weder Wort noch Zahl noch HTML -- zulassen.
   } else {
      // Bis hier nichts erkannt; also ein Fehler. Wir holen ein Dutzend Zeichen aus dem
      // HTML-Text ab der aktuellen Position und geben damit eine Fehlermeldung aus.
      m.usePattern(Pattern.compile("\\G(?s).{1,12}")).find();
      System.out.println("Unerwartetes HTML vor '" + m.group() + "'");
      System.exit(1);
   }
}

if (needClose) {
   System.out.println("Kein </A> am Ende.");
   System.exit(1);
}

Because of the bug in java.util.regex that would make the non-HTML match consume one extra character, I moved the non-HTML part to the end. The bug still occurs but affects only the error message, which is shifted by one character. I reported the bug to Sun.

While this bug remains, how could the one-argument version of find work around it? The answer is in Solution 15.

 

Processing CSV data

This is the java.util.regex version of the CSV example from The art of writing regular expressions (see Unrolling the loop for CSV data). For aesthetic reasons, however, we use possessive quantifiers rather than atomic groups.

String regex = // Werte in Anführungszeichen landen in group(1), solche ohne in group(2).
    "  \\G(?:^|,)    \n"+
    "  (?:           \n"+
    "       # Entweder ein Feld in Anführungszeichen ...       \n"+
    "       \" # Öffnendes Anführungszeichen    \n"+
    "        (   [^\"]*+  (?: \"\" [^\"]*+ )*+  )      \n"+
    "       \" # Schließendes Anführungszeichen    \n"+
    "   |# ... oder ...          \n"+
    "       # Ein Feld ohne Kommas und Anführungszeichen.       \n"+
    "       ( [^\",]*+ ) \n"+
    "  )             \n";

// Ein Matcher für eine Zeile CSV-Daten, mit obiger Regex.
Matcher mMain = Pattern.compile(regex, Pattern.COMMENTS).matcher(zeile);

// Ein Matcher für "", der Suchtext ist irrelevant.
Matcher mQuote = Pattern.compile("\"\"").matcher("");

while (mMain.find())
{
    String feld;
    if (mMain.start(2) >= 0)
        feld = mMain.group(2); // Feld ohne Anführungszeichen, kann direkt verwendet werden.
    else
        // Feld mit Anführungszeichen; verdoppelte durch einzelne ersetzen.
        feld = mQuote.reset(mMain.group(1)).replaceAll("\"");
    // Wert aus dem Feld weiterverarbeiten.
    System.out.println("Feld [" + feld + "]");
}

This version is more efficient than the original Java version under Parsing CSV files with Java for two reasons: the regex itself is optimized using the techniques in The art of writing regular expressions (see Unrolling the loop for CSV data), and we reuse one Matcher object, resetting it with reset rather than creating a new object each time.

  

 

 

 

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