XML technologies / Regular expressions / Practical regex techniques / A few short examples / Matching delimited text
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Matching quoted text or an IP address are just two instances of a general problem: recognizing text enclosed or separated by particular delimiters, often several characters long. Examples include:
C comments, using
›/*‹and›*/‹as delimitersHTML tags: text enclosed in angle brackets
(<...>), as in<CODE>.Extracting text between HTML tags, such as the text
›Hier●klicken!‹from the link›<A●HREF="...">Hier●klicken!</A>‹Recognizing a line from a .mailrc file, which may contain email aliases of the form
aliasKürzel volle-Adresse, such as
›alias jeff jfriedl@regex.info‹. (Here the delimiters are simply spaces between words and line endings.)Matching quoted text while allowing embedded quotes escaped with a backslash, as in:
a passport needs a "2\"x3\" photo" of the holder.Parsing CSV files (comma-separated values, a common database interchange format)
The general approach is:
Match the opening delimiter.
Match the actual text
(anything that is not the closing delimiter).Match the closing delimiter.
As you have seen, step 2 becomes tricky when delimiters contain multiple characters or can occur inside the text.
Allowing escaped quotes in quoted strings
In the example 2\"x3\", the delimiter is a double quote, but escaped quotes may occur inside. The opening and closing delimiters are single characters and easy to handle; the enclosed text is harder.
Clear reasoning helps: a nonquote character ( ˹[^"]˼) certainly matches. If it is a quote, it is allowed only when preceded by a backslash. Translating “when preceded by” literally into a lookbehind assertion (see Lookahead; lookbehind) gives ˹"([^"]|(?<=\\)")*"˼, which correctly matches the 2\"x3\" example.
But this also perfectly illustrates unintended matches creeping into a seemingly correct regex. It does not always work. We want it to match the underlined part of this rather silly text:
Darth-Symbol: "/-|-\\" oder "[^-^]"
Instead, it actually matches:
Darth-Symbol: "/-|-\\" oder "[^-^]"
A backslash really does precede the first string's closing quote. However, that backslash is itself escaped, so it does not escape the quote, which really is the closing delimiter. Our lookbehind does not recognize escaped escape characters, and an entire sequence of ›\\‹ sequences might precede it. Perhaps lookbehind was a poor choice. Escaped characters should be recognized during the initial scan, not afterward.
Focus on what is allowed between the delimiters: any escaped character ˹(\\.)˼, plus any character other than the delimiter ˹([^"])˼. This gives ˹"(\\.|[^"])*"˼.
Great, solved! Unfortunately, some strings still produce unwanted matches, for example when the closing quote is missing:
"You need a 2\"x3\" photo.
Why does this match? Recall the lesson from Greedy or lazy: a match takes priority. Initially, everything through the period is matched. But with no closing quote, the engine uses backtracking to return to this state:
in the text: | in the regex: |
At this point, ˹[^"]˼ matches the backslash, and the following quote is wrongly treated as the closing delimiter.
The lesson is:
If backtracking produces an unwanted match from an alternation, the wanted matches probably depend on the ordering of alternatives too.
Reversing the alternatives would prevent escaped quotes from being skipped. One alternative matches something intended for the other.
How can we fix it? As with continuation lines, ensure that a backslash can match only as intended. Thus, change ˹[^"] in ˹[^\\"]˼. Both the quote and backslash are special here and must be handled accordingly. The result ˹"(\\.|[^\\"])*"˼ works. (A working regex can often be made more efficient for an NFA; this example reappears under The art of writing regular expressions; see A sobering example.)
This example therefore teaches:
Building a regex requires considering what should not match, especially unexpected or invalid data.
The regex works, but other repairs are possible. With possessive quantifiers (see Possessive quantifiers) or atomic groups (see Atomic parentheses), it could be replaced by ˹"(\\.|[^"])*+"˼ or ˹"(?>(\\.|[^"])*)"˼. Both work, but conceal rather than solve the problem: they simply prevent backtracking to the problematic positions.
Understanding why these constructs help is valuable. We will nevertheless continue with the first repair, which is more generally applicable. We could actually also apply a possessive quantifier or atomic group to that first repair, to improve efficiency by detecting failure sooner, rather than to solve the already eliminated problem.
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
F
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