XML technologies / Regular expressions / Extended introductory examples / Modifying text with regular expressions / Converting plain text to HTML

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

Let’s write a small program to convert ordinary text to HTML. A general-purpose program that meets every possible need is difficult to write; here we will create a simple version for learning.

All previous examples applied regular expressions to text one line at a time. For this problem, it is much easier and more interesting to have the entire text available as one long string in a variable. In Perl this is done as follows:

undef $/; $text = <>;

# »Ganze Datei«-Modus aktivieren.
# Die gesamte auf der Befehlszeile angegebene Datei einlesen.

If our sample file contains just these three lines:

 Eine Beispieldatei. 
 Mit drei Zeilen. 
 Das ist alles. 

then after reading the file, the variable $text has the following value:

Eine Beispieldatei.NLMit drei Zeilen.NLDas ist alles.NL

Depending on the operating system used, it may instead have this value:

Eine Beispieldatei.CR NLMit drei Zeilen.CR NLDas ist alles.CR NL

Most systems use newline as the line-ending character, but some, such as Windows, use a combination of carriage return and newline. We will design our program to work with both.

Special handling for certain characters

First, we must make the characters ›&‹, ›<‹, and ›>‹ harmless by encoding them, as HTML requires, as ›&amp;‹, ›&lt‹, and ›&gt‹. These characters have special roles in HTML. Without encoding, they would often produce garbled output on screen.

$text =~ s/&/&amp;/g; $text =~ s/</&lt;/g;  $text =~ s/>/&gt;/g;

# Die HTML-Zeichen ...
# ... &, < und > ...
# ... unschädlich machen.

Again, we use /g to encode every occurrence in the file. It is important to handle & first, because the replacement text in all three cases itself contains ›&‹.

Splitting text into paragraphs

Next, we split the text into paragraphs by inserting the HTML tag <p> between them. In ordinary plain text, paragraphs are separated by blank lines. There are several ways to find blank lines. We might be tempted to use something like this:

$text =~ s/^$/<p>/g;

We look for the start of a line immediately followed by its end. With a tool such as egrep, which always reads text line by line, that would work, as you saw in Solution 1. It would also have worked in the earlier email example using Perl, since there we ensured that the subject string contained only one logical line of the email.

But as I mentioned in the note under A small mail program, ˹^˼ and ˹$˼ normally refer not to logical line starts and ends, but to the positions at the start and end of the entire subject string. (Note: ˹$˼ is usually a little more complicated, but that does not matter in this example. More details appear in the section on line anchors.) Here, however, we have several logical lines in a single string, so we need another approach.

Fortunately, most programming languages with regular expressions offer a multiline mode in which ˹^˼ and ˹$˼ refer to logical line starts and ends within a string. In Perl, this uses the modifier /m:

$text =~ s/^$/<p>/mg;

Notice how the modifiers /m and /g are combined. With multiple modifiers, order does not matter. For how this works in other languages, see Features and dialects.

If, for example, our variable $text contains ›...Kapitel.NLNLWenn...‹, it becomes ›...Kapitel.NL<p>NLWenn...‹.

But even this fails if the “blank” line contains spaces or other whitespace. We can allow spaces with ˹^●*$˼, or spaces, tabs, and the carriage returns that some systems place before a newline with ˹^[●\t\r]*$˼. But these expressions differ fundamentally from plain ˹^$˼, since they match actual text rather than just a position in the string. That does not matter here, since we do not need the whitespace characters and can replace them with the <p> tag.

Remembering the metacharacter ˹\s˼ from the section Whitespace with \s, you might think of using ˹^\s*$˼. But substituting ˹\s˼, which also matches newlines, for ˹[●\t\r]˼ changes the meaning of the regex. It now matches not only lines containing whitespace or nothing at all, but also sequences of lines containing whitespace or nothing at all. Thus, consecutive blank lines are matched by a single ˹^\s*$˼ and replaced by a single <p>. That is good here: otherwise we would get consecutive <p> tags with no text between them. If our variable $text contains the string

... dazwischen.NLNLNLTAB●NLWenn ...

and we apply the following substitution:

$text =~ s/^[ \t\r]*$/<p>/mg;

we get:

... dazwischen.NL<p>NL<p>NL<p>NLWenn ...

But if we use

$text =~ s/^\s*$/<p>/mg;

, we get the desired result:

... dazwischen.NL<p>NLWenn ...

So our final program will use ˹^\s*$˼.

 

Linking email addresses

Next, our text-to-HTML converter will learn to recognize email addresses and turn them into mailto links. An address such as “jfriedl@oreilly.com” should become <a●href="mailto:jfriedl@oreilly.com">jfriedl@oreilly.com</a>.

Recognizing email addresses with a regex is a very common practical need. The exact email-address specification is highly complicated and correspondingly hard to express as a regex. Accepting a solution that recognizes the usual forms makes the problem much simpler. Email addresses basically have the form “username@hostname”. We will develop subexpressions for the two parts later, but the overall substitution into mailto links will be:

$text =~ s/\b(username­regex\@hostname­regex)\b/<a href="mailto:$1">$1<\/a>/g;

First, I have highlighted two backslashes: one in the regex (›\@‹) and one near the end of the replacement text. They are needed for different reasons. The first kind will be discussed later; for now, it is enough to know that Perl requires @ characters in a regex to be escaped.

The backslash before ›/‹ in the replacement text is easy to understand. Perl’s substitution operator uses slashes to delimit the regex, replacement text, and any modifiers: s/Regex/Ersatztext/Modifikatoren. A slash inside one of the parts must be escaped with a backslash so Perl knows it is not a delimiter. Thus, to put <a> in the replacement text, we must write <\/a>.

That works but is not very attractive. Perl also allows us to choose our own delimiters, for example s!Regex!Ersatztext!Modifikatoren or s{Regex}{Ersatztext}Modifikatoren. Neither example uses its delimiter characters inside the regex or replacement text, so no escaping is required. The second encloses the regex and replacement text in braces. We will use this form more often from now on.

Notice that the entire address is wrapped in ˹\b...\b˼. The word boundaries avoid matches inside words, such as ›jfriedl@oreilly.compiler‹. Such nonsense is rare in normal text, but two small metacharacters provide cheap protection. Also note the capturing parentheses around the entire address. They are needed because the replacement uses their captured text: ›<a●href="mailto:$1">$1</a>‹.

 

Username and hostname

We now turn to the actual components of an email address and develop regular expressions for username and hostname. Hostnames such as regex.info and www.oreilly.com consist of dot-separated parts, the last of which is ›com‹, ›edu‹, ›info‹, ›de‹, and so on. A very simple regex for an entire email address would be ˹\w+\@\w+(\.\w+)+˼, allowing any “word,” namely ˹\w+˼, for the username and each hostname part. This is hardly practical. Usernames often contain dots and hyphens, though very rarely at the start. So instead of ˹\w+˼, we should use ˹\w[-.\w]*˼. The matched username starts with a ˹\w˼ character, but subsequent characters may include dots and hyphens. Notice that the hyphen comes first in the character class so it is interpreted literally rather than as a range metacharacter, as in ›a-z‹. Depending on the implementation and character set, the range ›.-\w‹ includes many special characters.

The hostname part is more complicated because dots are separators. Something must occur between the dots for them to separate. That is why even our first simple approach used ˹\w+(\.\w+)+˼ rather than just ˹[\w.]+˼. The latter would allow hostnames such as ›..x..‹, but even the first recognizes things such as ›Drehmoment 117Nm@6.750/min‹, so we need to be more precise.

We might, for example, enumerate the permissible final components, using something like ˹\w+(\.\w+)*\.(com|edu|info)˼. The list should actually include com|edu|gov|int|mil|net|org|biz|info|name|museum|coop|aero|[a-z][a-z], but I want to keep the examples short. The first component must match ˹\w+˼; further components of the same structure are allowed by ˹\.\w+˼, and one of the listed strings must appear at the end.

In fact, ˹\w˼ is not quite right. It allows ASCII letters and digits, but depending on the system and settings, ˹\w˼ may also allow non-ASCII characters such as à, ç , Ξ or Æ, and most regex dialects also allow underscores. None of these may appear in a hostname. We should therefore use ˹[a-zA-Z0-9]˼ or, together with the /i modifier, ˹[a-z0-9]˼. Hostnames may contain hyphens, however, so we use ˹[-a-z0-9]˼, again ensuring the hyphen is first in the class. The hostname part thus becomes ˹[-a-z0-9]+(\.[-a-z0-9]+)*\.(com|edu|info)˼.

As with all examples, the context in which the regex is used matters. On its own, ˹[-a-z0-9]+(\.[-a-z0-9]+)*\.(com|edu|info)˼ would also match a string such as ›Beim Booten C:\\startup.command ausführen‹, but the program’s wider context ensures that the subexpression matches only where intended. We can now insert it into the earlier

$text =~ s{\b(username-regex\@hostname-regex)\b}{<a href="mailto:$1">$1</a>}gi;

 

template. We have also chosen different delimiters s{...}{...} and the modifier /i, but it would never fit on one line. Perl does not care about excessively long or ugly lines, but I do. So I will introduce the /x modifier, which lets us write the regex as follows:

$text =~ s{
  \b 
  # Adresse in $1 abspeichern ... 
  ( 
    username-regex 
    \@ 
    hostname-regex 
  ) 
  \b 
}{<a href="mailto:$1">$1</a>}gix;

That looks much better! The modifier /x at the very end, here combined with /g and /i, does two things: it ignores whitespace in the regex, allowing a freer layout, and it permits # comments inside the regex.

With /x , most whitespace characters become “ignore me” metacharacters, and # becomes “ignore me and everything up to the end of the line” (see Free-spacing mode). Inside character classes these remain ordinary characters, so classes cannot use free-form layout, even with /x. As with other metacharacters, a preceding backslash yields the literal character. And ˹\s˼ still works as the whitespace metacharacter, for example in m/<a \s+ href=...>/x.

The /x applies only to the regex, not the replacement text. Although we use the brace form (s{...}{...}) instead of slashes, and put the modifiers after the second closing brace, as in ›}x‹, we still call the x modifier “/x”.

 

Putting it together

We can now insert the username and hostname subexpressions into the program developed earlier:

undef $/;                # »Ganze Datei«-Modus aktivieren.
$text = <>;              # Die gesamte auf der Befehlszeile angegebene Datei einlesen.

$text =~ s/&/&amp;/g;    # Die HTML-Zeichen ...
$text =~ s/</&lt;/g;     # ... &,  <  und  > ...
$text =~ s/>/&gt;/g;     # ... unschädlich machen.
$text =~ s/^\s*$/<p>/mg; # In Abschnitte aufteilen.

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

print $text;                                    # Fertig; HTML ausgeben.

All regexes apply to the same string, which contains several logical lines, but only the paragraph-splitting regex needed the /m modifier, since only that regex contains a ˹^˼ or a ˹$˼. In the other cases, /m would not have hurt, except that a reader might wonder why /m was used.

Linking HTTP URLs

As a final enhancement, we will also turn ordinary HTTP URLs into hyperlinks. A URL such as "http://www.yahoo.com/" should become this link: <a●href="http://www.yahoo.com/">http://www.yahoo.com/</a>.

The basic form of an HTTP URL is “http://Hostname/Pfad”, where the /Pfad part is optional. We start with this template:

$text =~ s{
   \b
   # URL in $1 abspeichern ...
   (
      http:// Hostname
      (
         / Pfad
      )?
   )
}{<a href="$1">$1</a>}gix;

The hostname part uses the same subexpression as the email address. A URL path can contain many different characters; in Expanding the foundations we used ˹[-a-z0-9_:@&?=+,.!/~*'%$]*˼: almost all ASCII characters except whitespace, control characters, and <, >, (, ), { and }.

In Perl, we must again escape @ and $ with backslashes; once again, we will postpone that discussion. Now insert the hostname and path parts:

$text =~ s{
   \b
   # URL in $1 abspeichern ...
   (
      http:// [-a-z0-9]+(\.[-a-z0-9]+)*\.(com|edu|info) \b # Hostname
      (
         / [-a-z0-9_:\@&?=+,.!/~*'%\$]*  # Optionaler Pfad-Teil
      )?
   )
}{<a href="$1">$1</a>}gix;

Notice there is no ˹\b˼ at the end of the path, since some paths do not end with an alphanumeric character. For example, O’Reilly’s URL for this book is "http://www.oreilly.de/catalog/regex3ger/". A final ˹\b˼ would exclude such URLs.

Still, allowing all those characters at the end of a URL is usually undesirable. In text such as

Schräge Neuigkeiten gibt es bei "http://dailynews.yahoo.com/h/od", technische News bei "http://www.slashdot.com!"

our regex would match the highlighted text, although a human reader can see that neither the comma nor the exclamation mark belongs to the URL. When URLs occur in ordinary text, it is probably wiser to require that they not end with ˹[.,?!]˼. No standard requires this; it simply handles most cases well. A negative lookbehind ˹(?<![.,?!])˼ at the end of the path seems ideal. At the end of the URL, the regex engine must look back because of the lookbehind and inspect the last matched character again. If the character fails the test, the engine must give back one character so the negative lookbehind can succeed. We will discuss another solution in Regex techniques in practice.

 

Inserting the regex gives us the finished program:

undef $/;                   # »Ganze Datei«-Modus aktivieren.
$text = <>;                 # Die gesamte auf der Befehlszeile angegebene Datei einlesen.

$text =~ s/&/&amp;/g;       # Die HTML-Zeichen ...
$text =~ s/</&lt;/g;        # ... &,  <  und  > ...
$text =~ s/>/&gt;/g;        # ... unschädlich machen.

$text =~ s/^\s*$/<p>/mg;    # In Abschnitte aufteilen.

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

# HTTP-URLs in Links verwandeln ...
$text =~ s{
   \b
   # URL in $1 abspeichern ...
   (
      http:// [-a-z0-9]+(\.[-a-z0-9]+)*\.(com|edu|info) \b  # Hostname.
      (
         / [-a-z0-9_:\@&?=+,.!/~*'%\$]*                     # Optionaler Pfad.
           (?<![.,?!])                                      # Darf nicht mit [.,?!] enden.
      )?
   )
}{<a href="$1">$1</a>}gix;

print $text;                                                # Fertig; HTML ausgeben.

 

A regex library

Notice that the same regex is used for both hostnames. Changing one means remembering to update the other. In the following program fragment, $HostnameRegex occurs three times:

$HostnameRegex = qr/[-a-z0-9]+(\.[-a-z0-9]+)*\.(com|edu|info)/i;

# E-Mail-Adressen in Links verwandeln ...
$text =~ s{
   \b
   # Adresse in $1 abspeichern ...
   (
     \w[-.\w]*                             # Username.
     \@
     $HostnameRegex                        # Hostname.
   )
   \b
}{<a href="mailto:$1">$1</a>}gix;

# HTTP-URLs in Links verwandeln ...
$text =~ s{
   \b
   # URL in $1 abspeichern ...
   (
      http:// $HostnameRegex \b            # Hostname.
      (
         / [-a-z0-9_:\@&?=+,.!/~*'%\$]*    # Optionaler Pfad.

           (?<![.,?!])                     # Darf nicht mit [.,?!] enden.
      )?
   )
}{<a href="$1">$1</a>}gix;

The first line introduces Perl’s qr operator. Like the m and s operators, it takes a regex as its argument: it is used as qr/.../, just like m/.../ and s/.../.../. But rather than immediately applying the regex to text to find a match, it turns it into a regex object that can be stored in a variable. This variable can later replace a regex or become a subexpression of a larger one. Here, for example, the regex object stored in $HostnameRegex is used within the regex of two substitutions. This makes the program much clearer. Now a hostname regex change needs to be made in only one place. More examples of this kind of regex library appear in The art of writing regular expressions, with a detailed description in Perl.

Other languages provide different ways to create regex objects. We will briefly touch on some of these in Features and dialects, and discuss Java and .NET in Java and .NET.

Why $ and @ sometimes need escaping

You have probably noticed that the dollar sign is both the end-of-line metacharacter and a way to insert variable contents into regexes, or interpolate variables. Usually there is no ambiguity, but character classes make things trickier. An end of line makes no sense inside a character class, so Perl treats the dollar sign as a request to interpolate a variable—unless it is escaped with a backslash (\$). That is why we had to escape the dollar sign in the HTTP URL subexpression.

Something similar happens with @. In Perl, @ starts an array name, and regexes and quoted strings normally interpolate arrays, inserting their values. For a literal @ in a regex, we must escape it so Perl does not try to interpolate an array. Some languages do not support array interpolation, including Java, VB.NET, C, C#, Emacs, and awk; others do, including Perl, PHP, Python, Ruby, and Tcl, each in a different way. This is explored further in Features and dialects.

  

 

 

 

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