XML technologies / Regular expressions / Practical regex techniques / HTML examples / Matching an HTML link

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

We want to extract each link’s URL and link text from an HTML file: the underlined parts here.

...<a href="http://www.oreilly.de">O'Reilly Verlag</a>...

Because a <A> tag can contain many different things, I use two steps. First extract the <A> contents and the link text, then extract the URL from those <A> contents.

My initial approach uses case-insensitive matching, dot-matches-all mode, and a lazy star: ˹<a\b([^>]+)>(.*?)</a>˼. The contents go into $1 and the link text into $2. I should of course replace ˹[^>]+˼ with the expression built in the previous section; the simple form merely keeps this example clear.

Once the <A> tag’s contents are in a string, another regex can examine them. The URL occurs in the attribute href=Wert. HTML permits whitespace on either side of the equals sign, and optionally quoted values, as we saw previously. The following Perl program prints the URL and link text of every link in $Html:

# Die Regex in der while-Bedingung ist zu einfach -- siehe Text
while ($Html =~ m{<a\b([^>]+)>(.*?)</a>}ig)
{
  my $Innereien = $1; # Resultate aus dem ersten Matching werden in separate ...
  my $LinkText  = $2; # ... Variablen abgespeichert.
  if ($Innereien =~ m{
                      \b HREF       # "href"-Attribut.
                      \s* = \s*     # Whitespace zu beiden Seiten des = erlaubt.
                      (?:           # Der Wert ist ...
                        "([^"]*)"   #   ein String in Anführungszeichen
                        |           #   oder ...
                        '([^']*)'   #   ein String in Hochkommas
                        |           #   oder ...
                        ([^'">\s]+) #   "anderes Zeug".
                      )             #
                     }xi)
  {
    my $Url = $+; # Der gefundene Klammerinhalt mit der höchsten Nummer von $1, $2 usw.
    print "URL $Url mit Link-Text: $LinkText\n";
  }
}

A few notes:

Depending on the HTML, the URL is saved in $1, $2 or $3; the others remain empty or undefined. Perl provides a special variable for exactly this purpose, $+, holding the text captured by the last capturing group that actually captured anything. Here, that is the URL.

Perl uses $+; other languages have other options. Ordinary language features can inspect captured groups and select the last nonempty one. If named groups (see Named subexpressions) are supported, they are ideal here, as the following VB.NET fragment shows. Fortunately .NET supports them, since its $+ does not work correctly; see the box Special dollar sequences in replacement text.

 

A link checker in VB.NET

This program prints URLs and link text from Html:

Imports System.Text.RegularExpressions
   ' Reguläre Ausdrücke definieren, die später in der Schleife verwendet werden.
Dim A_Regex as Regex = New Regex("<a\b(?<Innerei>[^>]+)>(?<Link>.*?)</a>", _
                                 RegexOptions.IgnoreCase)

Dim InnereiRegex as Regex = New Regex( _
   "\b HREF                (?#  'href'-Attribut                       )" & _
   "\s* = \s*              (?#  '=' mit Whitespace                    )" & _
   "(?:                    (?#  Der Wert ist ...                      )" & _
   "  ""(?<url>[^""]*)""   (?#    ein String in Anführungszeichen     )" & _
   "  |                    (?#    oder ...                            )" & _
   "  '(?<url>[^']*)'      (?#    ein String in Hochkommas            )" & _
   "  |                    (?#    oder ...                            )" & _
   "  (?<url>[^'"">\s]+)   (?#    'anderes Zeug'.                     )" & _
   ")                      (?#                                        )",  _
   RegexOptions.IgnoreCase OR RegexOptions.IgnorePatternWhitespace)

' Die ›Html‹-Variable absuchen ...
Dim CheckA as Match = A_Regex.Match(Html)

' Für jeden gefundenen Treffer ...
While CheckA.Success
   ' <a>-Tag gefunden, jetzt extrahieren wir daraus die URL.
   Dim UrlCheck as Match = InnereiRegex.Match(CheckA.Groups("Innerei").Value)
   If UrlCheck.Success
      ' Treffer, also haben wir ein URL/Link-Paar.
      Console.WriteLine("Url " & UrlCheck.Groups("url").Value & _
                        " mit Link-Text: " & CheckA.Groups("Link").Value)

   End If
   CheckA = CheckA.NextMatch
End While

A few remarks:

  • In VB.NET, first import the regex library with Imports .

  • I use comments of the form ˹(?#...)˼ because inserting a newline into a VB.NET string is awkward. Ordinary comments beginning with ›#‹ extend to the next newline or end of string, commenting out the entire remaining regex. Ordinary comments using ˹#...˼ would require &chr(10) at the end of every line (see Regex options).

  • Each ›"‹ in the regex requires ›""‹ in the string literal (see Strings in VB.NET).

  • Both regexes use named subexpressions, providing more meaningful names than merely Groups(1), Groups(2) and so on.

  

 

 

 

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