XML technologies / Regular expressions / The art of writing regular expressions / Unrolling the loop / Method 2: examining the critical loop in context
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
I said there were two ways to unroll a loop, producing the same regex. This second approach starts with the most frequent input elements and then handles rarer cases. Consider what the never-ending ˹(\\.|[^\\"]+)*˼ actually does and when it is used. A quoted string usually contains more ordinary than escaped characters, so ˹[^\\"]+˼ matches most of it. ˹\\.˼ is needed only for rare cases. Alternation handles both conveniently, but does disproportionate work even on strings with no escaped characters, probably the majority.
˹[^\\"]+˼ usually matches the entire string interior, after which a quote or backslash follows. With a backslash, we also want the next character, whatever it is, then more ordinary text matched by ˹[^\\"]+˼. After each ˹[^\\"]+˼, the same situation recurs: a closing quote or another backslash follows.
Translating this view directly into regex syntax gives the same expression as Method 1:
˹"[^\\"]+(▵\\.[^\\"]+)*"˼
Whenever we reach the point marked ▵, a quote or backslash follows. If it is a backslash, consume it, the following character, and more text until another quote-or-backslash point.
As in method 1, escaped characters may be consecutive or immediately follow the opening quote. The same reasoning replaces pluses with stars and gives the identical regex from General procedure for unrolling loops.
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