XML technologies / Regular expressions / The art of writing regular expressions / Unrolling the loop / Unrolling C comments
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
I now want to show an example where unrolling the critical loop is more difficult. In C, comments start with /* and end with */. They can span multiple lines but cannot nest. C++, Java, C#, and PHP also have this comment style. A regex matching C comments can be useful, even just for a filter removing them. This problem first led me to unrolling loops, a technique that has since become a permanent part of my regex arsenal.
To unroll or not…
I developed the unrolling technique in the early 1990s. Previously, a regex for C comments was considered difficult, if not impossible, so my solution quickly became standard. When lazy quantifiers appeared in Perl, a much simpler approach became available: a lazy dot in ˹/\*.*?\*/˼.
Had lazy quantifiers existed earlier, I probably would never have discovered unrolling loops, since the problem would not have seemed pressing. Nevertheless, unrolling remained valuable even with early lazy quantifiers, producing regexes from 50% faster to 3.6 times as fast, depending on the test.
With Perl’s current highly optimized regex engine, that lead has vanished. In modern Perl, the lazy-quantifier version ranges from 50% faster to 5.5 times as fast. For a problem such as C comments, I now use the simpler expression ˹/\*.*?\*/˼.
Does that make unrolling useless? It remains the first choice in dialects without lazy quantifiers. Also, few engines are as well optimized as Perl’s: in every other language I tested, unrolling was faster, sometimes by a factor of 60! The technique is certainly useful, so the rest of this chapter illustrates it thoroughly with C comments.
C comments have no backslash-escaped characters as quoted strings do, so things should be simpler. Unfortunately they are not, because */, the “closing quote”, contains more than one character. A crude approach such as ˹/\*[^*]*\*/˼ fails, because a line such as /** Das ist ein Kommentar **/ legitimately contains extra ›*‹, especially the penultimate star. We need a more nuanced approach.
Eyestrain
Expressions such as ˹/\*[^*]*\*/˼ are extremely hard to read. So many backslashes and stars hurt the eyes. Unfortunately, star belongs to both the delimiter and regex metacharacters. To improve readability, I will now use /x...x/ instead of /*...*/ as the comment delimiter. This purely cosmetic change turns ˹/\*[^*]*\*/˼ into the more readable ˹/x[^x]*x/˼. The expressions will grow more complicated, and your eyes will thank you.
A direct approach
In Practical regex techniques (under Matching delimited text), I recommended this approach to delimited text:
Match the opening delimiters.
Match the actual text: everything not part of the closing delimiter.
Match the closing delimiters.
Our pseudocomments, opened by /x and closed by x/, seem to fit. The difficulty lies in translating “everything not part of the closing delimiter”. With single-character delimiters, a negated character class suffices. A class cannot handle multicharacter delimiters, but with negative lookahead one can use something like ˹(?:(?!x/).)*˼. In words, this is roughly ˹(alles, aber nicht x/)*˼.
This gives the regex ˹/x(?:(?!x/).)*x/˼ for C comments. It works well but is somewhat slow: in some tests, hundreds of times slower than the fastest version we will develop. It is also uninteresting because almost every dialect supporting lookahead also supports lazy quantifiers. If efficiency matters, use ˹/x.*?x/˼ instead.
Following the three steps above, is there another way to match everything up to the first x/? There are two common ways to match up to the next x/ . One treats x as the closing delimiter’s beginning. It looks for everything except x, and also allows an x if no slash follows. Thus, “everything not part of the closing delimiter” becomes:
Anything except
x:˹[^x]˼xunless followed by a slash:˹x[^/]˼
This gives ˹([^x]|x[^/])*˼ for the actual text and ˹/x([^x]|x[^/])*x/˼ for the whole pseudocomment. But we will see that it fails.
The other approach treats slash as the terminator, but only when preceded by an x. The formulation then becomes:
Anything except a slash:
˹[^/]˼A slash, unless preceded by
x:˹[^x]/˼
This gives ˹([^/]|[^x]/)*˼ for the actual text and ˹/x([^/]|[^x]/)*x/˼ for the whole comment.
Unfortunately, that fails too.
For the first case, ˹/x([^x]|x[^/])*x/˼, consider ›/xx●foo●xx/‹. After ›foo●‹ is matched, the penultimate x matches ˹x[^/]˼; so far, so good. But then ˹x[^/]˼ matches the text xx/, which contains the x belonging to the terminator. Matching therefore skips that terminator and continues to the next comment’s end, if any.
For ˹/x([^/]|[^x]/)*x/˼, a counterexample is ›/x/●foo●/x/‹. This is one comment and should match. This regex also overshoots when a slash immediately follows the terminator, similarly to the previous approach. The resulting backtracking is quite complicated, so I leave it to you to discover why the regex ˹/x([^/]|[^x]/)*x/˼ matches the following:
jahre = tage /x div x//365; /x kein Schaltjahr x/
Repairs
Let us see whether we can patch these expressions. In the first, ˹x[^/]˼ unintentionally matches ...xx/ belonging to the delimiter. In ˹/x([^x]|x+[^/])*x/˼, plus would let ˹x+[^/]˼ match a whole series of x followed by something other than slash. That does happen, but backtracking allows that “something other than slash” to be another x. Initially, the greedy ˹x+˼ really does match the final x, but backtracking relinquishes it because doing so allows the entire expression to match. Too much is matched in a string like:
/xx A xx/ foo() /xx B xx/
The solution recalls something I emphasized before: Say exactly what you mean. When we say “ x followed by a nonslash”, we implicitly mean that this nonslash must not be an x either. So write exactly that: ˹x+[^/x]˼. As intended, this stops before ›...xxx/‹, the final x before a slash. More precisely, it stops before any x, at ›...▵xxx/‹. But the terminator subexpression expects only x, so we must add plus to recognize this case too.
This gives ˹/x([^x]|x+[^/x])*x+/˼, an expression matching our pseudocomments.
Translating prose into regexIn A direct approach, we discussed two methods of finding C comments, using the descriptions
and
These are informal: the prose differs considerably from what the regexes actually do. Do you see the difference? For the first case, consider the string With lookahead, “ We will use none of these methods for C comments, but knowing how they work is useful. |
Whew! Confusing, isn’t it? For real comments, with * instead of x, we need
˹/\*([^*]|\*+[^/*])*\*+/˼
, which looks even worse. Complicated regexes really do require concentration to read!
Unrolling the C loop
To improve efficiency, we will unroll this loop too. The table gives the subexpressions to insert into our recipe.
Table: unrolling the loop, components for C comments.
Element | What we want | Regex |
|---|---|---|
| ||
opening | comment start |
|
normal* | comment text through one or more ›x‹ characters |
|
special | something other than slash or ›x‹ |
|
closing | final slash |
|
As with Internet domains, the element ˹normal*˼ must not match nothing. Domain names cannot be empty strings; here, the reason is how multicharacter delimiters are handled. We ensure every normal sequence ends with the first character of the two-character delimiter. Also, special must not match either character making up that delimiter.
Inserting these into the framework gives:
˹/x[^x]*x+(▵[^/x][^x]*x+)*/˼
See the marked position? The engine can reach it two ways, just as in the expression in Method 2: examining the critical loop in context: on the first pass, by processing the initial ˹/x[^x]*x+˼, or through the loop formed by the star in (...)*. Either way, we reach a checkpoint: an x has just matched, perhaps just before the comment’s end. If the next character is slash, we are done. If it is something else, but not another x, the x was a false alarm, so we can continue to the next x or run of them. We then return to exactly the same position in the regex.
Back to reality
˹/x[^x]*x+([^/x][^x]*x+)*/˼ is not quite ready for use. Real comments look like /*...*/ , not /x...x/. This is trivial: replace x with \*, or just * inside a character class:
˹/\*[^*]*\*+([^/*][^*]*\*+)*/˼
C-style comments often span multiple lines. If the subject contains several logical lines with newlines, there is no problem: our regex still works. With strictly line-oriented tools such as egrep , little can be done; most other programs can use this regex for multiline comments, for example to remove them.
A much trickier practical problem remains: our regex knows C comments but nothing about the rest of a C program’s structure. In particular, it knows nothing about C strings and therefore stumbles on lines such as:
const char *cstart = "/*", *cend = "*/";
We will develop this example further in the next section.
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