XML technologies / Regular expressions / Practical regex techniques / Detailed examples / Staying synchronized with the data

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

This longer, somewhat contrived example illustrates why the regex must stay synchronized with searched data, and how to achieve that.

Suppose the data are concatenated five-digit German postal codes. Find all codes starting with 66 . Sample data, with wanted codes in bold:

03824531669411615213661829503566706752010217663235

First, repeatedly apply ˹\d\d\d\d\d˼. In Perl, this is easy: @plz = m/\d\d\d\d\d/g creates an array of postal codes, assuming input is in the default subject $_; see Note on line 1 of Doubled words in Perl. Other languages repeatedly call a regex find method in a loop. Here I focus on regexes, not language-specific use, and illustrate with Perl.

Returning to ˹\d\d\d\d\d˼: importantly, it always matches immediately until data runs out. Since everything is digits, the transmission never advances a character. This assumes conforming data, an assumption sometimes true in practice, often not.

Simply changing ˹\d\d\d\d\d˼ to ˹66\d\d\d˼ cannot work. After failure, the transmission advances one character and loses synchronization, seeking ˹66...˼ rather than a five-digit boundary. With ˹66\d\d\d˼ a false match is found at ›...5316694116...‹, which is not a postal code.

A caret or ˹\A˼ would restrict matching to the first code. We need to stay synchronized while ignoring unwanted codes: skip whole codes manually, not individual digits as the transmission does.

 

Staying synchronized with expected data

Here are ways to skip unwanted codes. Prefix any of these to the subexpression matching wanted codes, ˹(66\d\d\d)˼. Unwanted codes use noncapturing groups; wanted ones are captured in $1.

˹(?:[^6]\d\d\d\d|\d[^6]\d\d\d)*...˼

This skips codes beginning with something other than 66 . More cautiously, use ˹[0-57-9]˼ instead of ˹[^6]˼, though we assume digit-only data. Note that ˹(?:[^6][^6]\d\d\d)*˼ fails to skip unwanted codes like 65432 .

˹(?:(?!66)\d\d\d\d\d)*...˼

This skips codes unless they begin with 66 . The wording resembles the previous solution, but the regexes differ. A wanted code beginning with 66 makes ˹(?!66)˼ fail, ending the skipping.

˹(?:\d\d\d\d\d)*?...˼

This uses a lazy quantifier, skipping codes only when forced by a later subexpression that must match. Minimal matching applies ˹(?:\d\d\d\d\d)˼ only when the following part fails, repeating until it succeeds locally.

Combine the last approach with ˹(66\d\d\d)˼ :

@plz = m/(?:\d\d\d\d\d)*?(66\d\d\d)/g;

This selects codes beginning with ›66xxx‹ while actively skipping others. (In list context, “@array = m/.../g” returns every captured piece over all iterations; see Extracting all matches: list context with /g.) The regex works with the /g modifier because after each iteration of /g the current position begins a postal code.

 

Staying synchronized with unexpected data

Have we truly restricted attempts to postal-code boundaries? No! We manually skip unwanted codes between wanted ones beginning with 66 . After the final wanted code, the regex fails. The transmission then advances one character into a code, contradicting our assumption.

Revisit the sample data:

03824 53166 94116 15213661829503566706▵7▵5▵2▵010217663235

Matches are bold, the third unwanted; skipped codes are underlined, transmission positions marked. After matching 66706 , the regex finds no more matches. But the transmission advances character by character, losing synchronization. After four characters, the regex skips 10217 and wrongly treats 66323 as a code.

All three approaches require aligned starting positions, disrupted by normal transmission behavior. Prevent advancement or make it skip more than one character.

For the first two approaches, prevent advancement by making ˹(66\d\d\d)˼ optional with ˹?˼. The prefixes ˹(?:(?!66)\d\d\d\d\d)*...˼ or ˹(?:[^6]\d\d\d\d|\d[^6]\d\d\d)*...˼ stop only before a wanted code or when none remain, unlike the third approach. Thus ˹(66\d\d\d)?˼ matches a wanted code if present, without forcing backtracking.

This also matches empty strings when no code is found, requiring language-level filtering. It is fast, with little backtracking and no transmission advancement.

 

Staying synchronized with \G

More generally, prefix ˹\G˼ (see Start of the new or end of the previous search: \G) to any approach. Each subexpression ends at a postal-code boundary. With ˹\G˼, the transmission does not advance: most dialects require a new match to begin exactly where the previous one ended. Ruby instead interprets ˹\G˼ as the new match's start rather than the previous match's end; see Previous search's end or current search's start?.

The second approach gives a solution without filtering empty matches:

@plz = m/\G(?:(?!66)\d\d\d\d\d)*(66\d\d\d)/g;

 

This \G example in context

The example is contrived, but teaches useful synchronization techniques. In practice I would probably not use regexes alone. I might use ˹\d\d\d\d\d˼ to extract five-digit groups and check whether they begin with ›66‹ . In Perl:

@plz = ( ); # Leeres Array. 

while (m/(\d\d\d\d\d)/g) { 
   $plz = $1; 
   if (substr($plz, 0, 2) eq "66") { 
       push @plz, $plz; 
   } 
}

The box A Perl example using \G gives an interesting example of \G using features currently exclusive to Perl.

  

 

 

 

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