XML technologies / Regular expressions / Practical regex techniques / A few short examples / Continuation lines
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
In How regex engines work, the continuation-line example in Truly the longest match showed that a traditional NFA using ˹^\w+=.*(\\\n.*)*˼ on text
SRC=array.c builtin.c eval.c field.c gawkmisc.c io.c main.c \
missing.c msg.c node.c re.c version.cfails to find both lines. The first ˹.*˼ matches through the first backslash, hiding it from the intended ˹(\\\n.*)*˼. To stop at the backslash, we must tell the regex explicitly by replacing the dot with ˹[^\n\\]˼ . Notice that the negated class also includes \n. We assumed the dialect’s dot did not match newline; the replacement subexpression must respect that too (see Almost any character: dot).
We get:
˹^\w+=[^\n\\]*(\\\n[^\n\\]*)*˼
This works on the Makefile examples but may introduce a new problem: backslashes are now allowed only at line endings. A backslash in the middle of a line breaks the regex, yet that case must work too.
So far, we have sought one line and any following continuation lines. Let us try a different approach that has often worked for me: focus on the allowed characters at each position. Within a line, permit ordinary characters other than newline or backslash, or a backslash followed by anything. Using ˹\\.˼ with dot-matches-all mode also matches backslash followed by newline.
The expression becomes ˹^\w+=([^\n\\]|\\.)*˼, provided dot really matches every character. Depending on use, the leading ˹^˼ may require multiline mode too (see Enhanced line-anchor or multiline mode).
We are not quite done: The art of writing regular expressions discusses this example’s efficiency (see Examples of 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