XML technologies / Regular expressions / The art of writing regular expressions / The free-flowing regex

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

We have just built a regex that matches C comments but fails when quoted strings contain apparent comment delimiters that are not really delimiters. A Perl snippet like the following, intended to remove comments from C programs, may do too much:

$prog =~ s{/\*[^*]*\*+(?:[^/*][^*]*\*+)*/}{}g; # Entfernt C-Kommentare (und anderes!)

This removes, by replacing with nothing, whatever our regex matches from the text in $prog. But nothing prevents our regex from matching a comment marker inside a string:

char *CommentStart = "/*"; /* Kommentar-Anfang */ 
 char *CommentEnd = "*/"; /* Kommentar-Ende */ 

Here, the comments we wanted are bold, while what the regex actually finds is underlined. During a search, the expression is tried at every position in the string. Real matches can begin only at a comment opener, but the transmission moves the regex into a string to something that merely looks like an opener. It would help if we could make the regex simply ignore quoted strings.

 

A helping hand guides the engine

Consider this code:

$KOMMENTAR = qr{/\*[^*]*\*+(?:[^/*][^*]*\*+)*/};  # erkennt Kommentare
$GAENSE    = qr{"(?:\\.|[^"\\])*"};               # erkennt Strings in Anführungszeichen
$text =~ s/$GAENSE|$KOMMENTAR//g;

Two things are new. First, the regex operand $GAENSE|$KOMMENTAR is assembled from two variables, each initialized with Perl’s special qr/.../ operator. Care is needed when specifying regexes as strings, as mentioned in Features and dialects (see Strings as regular expressions).

Perl’s special qr/.../ operator interprets its operand as a regex rather than a string, but does not apply it. It returns a kind of regex object that can later be used within a larger expression. This is tremendously useful; we already exploited it in Extended introductory examples (under A regex collection). As with m/.../ and s/.../.../, you can choose the delimiters yourself (see Linking email addresses); I used braces here.

The other new feature is the $GAENSE part. If an attempt begins at a position where $GAENSE can match, it will, thereby skipping quoted strings. This works because the alternatives never overlap. At each possible starting position, one of these cases occurs:

  • The comment alternative matches, recognizing everything through a comment terminator. Or…

  • The quoted-string alternative matches, recognizing the entire string. Or…

  • Nothing matches. The uninteresting character is ignored and the transmission advances to the next.

Thus, the actual regex is never started inside a quoted string. That is the key. Unfortunately, the code currently removes strings from the C program as well as comments.

We can fix that too:

$KOMMENTAR = qr{/\*[^*]*\*+(?:[^/*][^*]*\*+)*/};  # erkennt Kommentare
$GAENSE    = qr{"(?:\\.|[^"\\])*"};               # erkennt Strings in Anführungszeichen
$text =~ s/($GAENSE)|$KOMMENTAR/$1/g;

The only differences from before are:

  • Additional capturing parentheses store the matched text in $1. When the comment alternative matches, \1 contains the empty string.

  • The substitution’s replacement string is now $1. If the $GAENSE alternative matches, it replaces itself: the substitution becomes a no-op, but moves the current position beyond the string, precisely why we introduced it. If the comment alternative matches instead, it is replaced with nothing, the empty string in $1. (Note: in Perl, if the first capturing group does not participate in a match, $1 receives a kind of “no value”, namely undef. Interpolated in replacement text, it acts like the empty string, exactly what we need here. But if you use -w or use warnings, as every good programmer does, this produces a warning. Avoid it by adding, in the block containing this regex, a ›no warnings;‹ pragma, or by testing explicitly for the special value undef: $text =~ s/($GAENSE)|$KOMMENTAR/defined($1) ? $1 : /ge;)

Finally, we must handle single-quoted constants such as '\t'. This is easy: add another alternative analogous to the double-quoted-string one. If the script should also handle // comments as in C++, Java, or C#, a fourth alternative ˹//[^\n]*˼ outside the parentheses does the job.

$KOMMENTAR  = qr{/\*[^*]*\*+(?:[^/*][^*]*\*+)*/};   # /*  C-Kommentar */
$KOMMENTAR2 = qr{//[^\n]*};                         # // C++/Java/C#-Kommentar
$GAENSE     = qr{"(?:\\.|[^"\\])*"};                # "String in Anführungszeichen"
$HOCHKOMMA  = qr{'(?:\\.|[^fl\\])*'};               # 'Hochkomma-String'
$text =~ s/($GAENSE|$HOCHKOMMA)|$KOMMENTAR|$KOMMENTAR2/$1/g;

This version is already quite fast. On my aging machine, vintage 1997, a small test removes comments from a 16 MB file of over 500,000 lines in 16.4 seconds. That is fast, but we will improve it further.

 

A well-guided regex is a fast regex

A little hand-holding can make the engine process this script considerably faster. Consider ordinary text: program lines containing neither comments nor strings. At every character, the engine tests each of the four alternatives, and only when all fail does the transmission advance. Much unnecessary work is done here.

We know each alternative must begin with one particular character: a slash, single quote, or double quote. That character alone does not establish that a comment or string actually begins, but without such a character, no alternative can possibly match. Rather than making the engine discover this painfully, we help the regex engine by adding ˹[^'"/]˼ as another alternative. We can actually test for several such characters at once, so we use ˹[^'"/]+˼ instead. If this triggers a warning light for an “eternal match”, that is true only inside a loop produced by (...)* or a variation thereof. Here, however, the [^'"/]+ stands alone: no following element can reclaim characters matched by backtracking. Hence there is no risk of an eternal match.

$SONST = qr{[^"'/]};  # keine der anderen Alternativen kann damit beginnen
  .
  . 
  .
$text =~ s/($GAENSE|$HOCHKOMMA|$SONST+)|$KOMMENTAR|$KOMMENTAR2/$1/g;

For reasons that will soon become clear, I placed the plus quantifier after $SONST rather than inside $SONST itself.

Repeating the test with this additional alternative, I found that this tiny change made the regex almost four times faster! Carefully constructing it avoids having to test all alternatives at every character before advancing. Cases such as ›c●▵/●3.14‹ still occur and are handled by the old, slow method.

But we can make it faster still.

  • The most frequently used alternative will probably be ˹$SONST+˼, so let us put it first. This makes no difference to a POSIX NFA, which must evaluate all alternatives anyway, but a traditional NFA stops as soon as it finds a match. Why make it search for relatively rare patterns longer than necessary?

  • A double- or single-quoted string is likely to be followed by characters from the class $SONST before another string or comment. Adding ˹$SONST*˼ to each string alternative tells the engine that the greedy star in $SONST can match many characters without returning to the outer loop formed by /g.

    This resembles unrolling the loop. Indeed, much of that technique’s speed gain comes from this aspect: we use our higher-level knowledge of C programs to program the engine for local efficiency.

    Note that it is very important for the first $SONST to use a plus quantifier and the others a star. Stars are necessary to recognize consecutive double- or single-quoted strings. If the plus were a star, the first $SONST would always match!

With these changes, we obtain:

˹($SONST+|$GAENSE$SONST*|$HOCHKOMMA$SONST*)|$KOMMENTAR|$KOMMENTAR2˼

This makes the script about another 5% faster.

Let us step back and consider the last two changes. Testing ordinary characters with $SONST* immediately after every matched string leaves the original $SONST+ used only in two situations: at the very beginning of the string and after each comment.

One is tempted to think: “We can cover the second case by appending $SONST* to the comment expressions too!” Yes, but that throws the baby out with the bathwater: the $SONST expressions must be captured inside the parentheses, since everything outside them is deleted.

But if the initial $SONST+ is needed only rarely—at the start and after comments—do we really want it first? That depends on the data. If comments outnumber quoted strings, the current version really is better. If the reverse is true, moving the subexpression later would be better. My test data favored the first choice; rearranging it undid about half the last step’s gain.

Summary

Are we finished? Not at all! The two string subexpressions are ideal candidates for unrolling loops. Having devoted a long section to that method, we should use it. Substituting the expressions

$GAENSE    = qr{"[^"\\]*(?:\\.[^"\\]*)*"};
$HOCHKOMMA = qr{'[^'\\]*(?:\\.[^'\\]*)*'};

into our framework saves another 15%. With only a few changes, runtime has fallen from 16.4 to 2.3 seconds: more than seven times faster.

This last change also shows how convenient and clear assembling a large regex from variables can be. Individual components, such as $GAENSE, can be built and modified independently, without distraction from other regex parts. Some tasks still require considering the whole regex, such as counting capturing groups, but this technique is extremely useful.

Perl’s qr/.../ operator provides further help, giving Perl something like double-quoted strings with an emphasis on regexes. Other languages lack this exact feature, but most offer a string type particularly suited to building regexes (see the section Strings as regular expressions).

You will especially appreciate assembling regexes this way when you see the complete expanded expression. It occupies two lines here for reasons of space:

([^"'/]+|"[^"\\]*(?:\\.[^"\\]*)*"[^"'/]*|'[^'\\]*
(?:\\.[^'\\]*)*'[^"'/]*)|/\*[^*]*\*+(?:[^/*][^*]*\*+)*/|//[^\n]*

  

 

 

 

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