XML technologies / Regular expressions / The art of writing regular expressions / Unrolling the loop / Method 3: an Internet hostname in quotation marks
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
I promised two methods for unrolling the critical loop; now I present what could be called a third. I discovered it while working with Internet domain names such as www.yahoo.com, essentially dot-separated lists of subdomain names. Exactly what a subdomain may contain is rather complicated (see Validating hostname syntax); for this example, we assume that such subdomain names must match the regex ˹[a-z]+˼ (a sufficient but not necessary condition).
If ˹[a-z]+˼ matches a subdomain and we want a dot-separated list, we must first match one subdomain. Further subdomains are then optional, but each needs a preceding dot. Translated into a regex, this is: ˹[a-z]+(\.[a-z]+)*˼. Written this way: ˹[a-z]+(\.[a-z]+)*˼, it looks rather familiar!
To explore the resemblance, compare this with the regex for quoted strings. We can view such a string as a sequence of ˹[^\\"]˼ (normal), separated by ˹\\˼. (speziell), all enclosed by ›"..."‹. Following the recipe gives ˹"[^\\"]+(\\.[^\\"]+)*"˼, which is again the regex we obtained with Method 1 and Method 2. We are taking the same principle as for a hostname—characters separated by delimiters—and applying it to quoted strings. The result is “sequences of unescaped characters separated by escaped characters”. This is hardly an obvious perspective, but it apparently leads to the same result.
The similarities are interesting, but there are differences too. In Method 1, we changed the regex to allow empty sequences of normal before and after a speziell . We cannot allow that here, because a subdomain cannot be empty. Although this example differs from the earlier ones, it belongs to the same class of problems and shows that loop unrolling is quite flexible.
There are two relevant differences between quoted strings and the subdomain example:
Domain names have no delimiters at either end.
The normal part of a domain name must never be empty: consecutive dots and dots at either end are forbidden. Quoted strings have no such restrictions. Their interior can be empty, can consist only of escaped characters, and can contain consecutive backslashes; we merely expect such strings to be uncommon. We could therefore replace
˹[^\\"]+˼with˹[^\\"]*˼. Domain names do not permit this: a dot is a mandatory separator here.
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