XML technologies / Regular expressions / How regex engines work / More on greediness / Possessive quantifiers and atomic groups

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

The ›.625‹ example from Greedy or lazy—matching comes first provides some important insights into how an NFA works and has shown how our naive approaches were thwarted. Some implementations offer features that could help us, but understanding the points on the preceding page, Greediness, laziness, and backtracking: the essence, is an absolute prerequisite. Please refer back to it if anything is unclear.

Back, then, to the ›.625‹ stock-price example. We want to control the regex so that, once the engine reaches the marked position ˹(\.\d\d[1-9]?)▵\d+˼ , it never goes back using backtracking. In other words, we want ˹[1-9]˼ to match whenever possible, and once it has matched, we never want that local match to be given up. We would rather have the entire match attempt fail than return any character once matched by ˹[1-9]˼. (Remember: when this regex was applied to ›.625‹, the engine did not give up; it returned to a saved state and found another, incorrect possibility.)

What if we could prevent just this “incorrect possibility” (that is, prevent the state for ˹?˼ from being saved just before trying ˹[1-9]˼ )? Without a saved state, a local match by ˹[1-9]˼ could no longer be given up. Yes, that is exactly what we need! What happens if we apply the regex to ›.5000‹? The ˹[1-9]˼ would no longer match, and in that case we want the engine to backtrack and skip the ˹[1-9]˼ so that the following ˹\d+˼ matches the surplus digits.

These almost sound like mutually exclusive wishes, but more precisely we only want the possibility “skip ˹[1-9]˼ ” to stop being considered once the possibility “˹[1-9]˼ matches” has succeeded. Once ˹[1-9]˼ has matched, its corresponding state should be removed from the list of saved states. This really is possible , at least with regex dialects supporting either atomic groups with ˹(?>...)˼ (see the section Atomic parentheses) or possessive quantifiers such as ˹[1-9]?+˼ (see the section Possessive quantifiers). We will look at atomic groups first.

 

Atomic groups with ˹(?>...)˼

Essentially, matching proceeds normally inside ˹(?>...)˼, but once the engine has successfully worked through the atomic parentheses (and thus reached the closing parenthesis), all states saved during that process are discarded. Consequently, the engine can never return to a decision point within those parentheses. The text matched by the group is now an indivisible unit that can only be relinquished as a whole, atomically. Every state corresponding to an untried path is removed when the group is exited successfully, putting those states beyond the reach of backtracking.

Consider our example with atomic parentheses, ˹(\.\d\d(?>[1-9]?))\d+˼. Quantifiers behave normally inside atomic parentheses. Thus, if ˹[1-9]˼ does not match, the engine returns to the state before the “match or skip” decision introduced by the ˹?˼. In that case, there are no saved states to discard when leaving the group: none remain that were saved while working through it.

If, on the other hand, the ˹[1-9]˼ matches a digit, the entire group matches on the first attempt, but the state saved by the question mark still exists. Since it was created inside the group, it is now discarded. This would happen, for example, with ›.625 ‹ or ›.625000‹. In the latter case, discarding the saved states makes no difference, because the following ˹\d+˼ matches ›.625000‹ and the regex engine need not backtrack. With ›.625‹, however, no text is found for ˹\d+˼ . The engine would like to reclaim digits by backtracking, but cannot: the state at the “match or skip” decision was discarded. No saved states remain at all, so the entire match attempt fails and, just as we intended, the ›.625‹ remains unchanged.

 

Atomic groups: the essence

In Greediness, laziness, and backtracking: the essence, we saw that greedy and lazy constructs do not affect which alternatives are tried; they only affect the order in which the possibilities are tested. If the entire search fails, every possible path has been explored, whether greedy or lazy.

Atomic groups change this conceptually, because previously possible paths are eliminated. Depending on the situation, discarding saved states can have several effects:

No effect

If a match is found before any eliminated state would have been tried, matching proceeds just as without atomic parentheses. This is exactly what we saw in the preceding section with ›.625000‹: an overall match was found without ever having to reactivate a saved state.

No match

Discarding states can itself cause the entire regex to fail. We saw this in the example with ›.625‹.

A different match

In certain cases, atomic parentheses guide the regex engine to a different possible match.

Faster failure

If no match is possible even without atomic parentheses, adding them may let the regex engine discover this faster, because it has fewer possibilities to test.

A short exercise: What does the construct ˹(?>.*?)˼ do? What sorts of things does it match? For the answer, see Solution 12.

Some states remain

When the regex engine has worked through an atomic group, it discards only the states saved during the atomic group. States that already existed remain untouched. Thus, the text matched by the entire atomic group can still be relinquished by backtracking.

 

Faster failures with atomic groups

When ˹^\w+:˼ is applied to ›Subject‹, we immediately see that it can never match, because the text contains no colon. The regex engine, however, reaches that conclusion only after many attempts.

By the time ˹:˼ is first tested, the ˹\w+˼ has traversed the entire string. Along the way, a whole series of states has been saved: one “skip me” state for every character in the string matched by ˹\w˼ and the plus sign (except the first, which is mandatory with plus). When the engine reaches the last character and the ˹:˼ fails, the engine returns to the most recent state:

in the text: ›Subjec▵t‹

in the regex: ˹^\w+▵:˼

At this point, the ˹:˼ does not match the ›t‹ either. This backtrack-and-test loop repeats until the engine reaches the oldest state:

in the text: ›S▵ubject‹

in the regex: ˹^\w+▵:˼

Here, too, the ˹:˼ does not match, and it is finally clear that the entire regex fails.

All this backtracking is a considerable amount of work that we can see at a glance is unnecessary. If the colon cannot match the last character, it certainly cannot match the word characters successively reclaimed by ˹+˼.

Knowing that the saved states are useless if the final colon fails, we can tell the regex engine so: ˹^(?>\w+):˼. The atomic parentheses express our “global knowledge”, improving the efficiency of the local ˹\w+˼. If a match is found, the atomic parentheses make no difference; otherwise, no saved states remain and the engine discovers much faster that no match is possible. (A good implementation can recognize this situation and perform this optimization automatically; see the section Automatic possessification.)

In The art of writing regular expressions (see Using atomic groups and possessive quantifiers), you will see how useful this technique can be; this is probably the most common use of atomic parentheses.

 

Possessive quantifiers: ?+, *+, ++ and {m,n}+

Possessive quantifiers are greedy, but also pathologically stingy: once they have matched something, they never give it back. By the time a subexpression quantified with plus has been processed, many states have been saved, as you just saw in the example with ˹^\w+˼. With a possessive plus sign, these states are immediately discarded (or never created in the first place).

As you may suspect, possessive quantifiers are closely related to atomic parentheses. A possessive expression such as ˹\w++˼ behaves like ˹(?>\w+)˼; it is mostly a matter of notation. (Note, however, that a good implementation can make the possessive version slightly more efficient than the corresponding atomic-parenthesis expression; see the section Automatic possessification.) With these stingy quantifiers, the example ˹^(?>\w+):˼ can be rewritten as ˹^\w++:˼, and ˹(\.\d\d(?>[1-9]?))\d+˼ becomes ˹(\.\d\d[1-9]?+)\d+˼.

Is the difference between ˹(?>M)+˼ and ˹(?>M+)˼ clear? In the first case, the unused states created by the ˹M˼ are discarded—but this is pointless, because ˹M˼ offers no choices at all and hence creates no states. In the second case, the states created by ˹M+˼ are eliminated, saving many possible paths.

Comparing ˹(?>M)+˼ with ˹(?>M+)˼ may make it clearer that the second expression is comparable to ˹M++˼. When converting more complicated possessive expressions such as ˹(\\"|[^"])*+˼ to atomic-group form, it is all too tempting simply to add ›?>‹ to the existing parentheses: ˹(?>\\"|[^"])*˼. This new expression might even achieve the goal, but it is not equivalent to the original possessive construct. The two versions behave like ˹M++˼ versus ˹(?>M)+˼. To obtain the equivalent atomic expression, remove the “stingy” plus and wrap the rest in atomic parentheses: ˹(?>(\\"|[^"])*)˼.

  

 

 

 

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