Atomic groups and possessive quantifiers

Advanced · 9 min

Stop the engine giving characters back. (?>...) and a++ work in PCRE, Perl, Java and Ruby. JavaScript has neither, but a lookahead can fake one.

Before thisCatastrophic backtracking and ReDoSGreedy and lazy quantifiersLookaheadBackreferencesCapturing groups and numbering

PyCon AU · 30 min · from 11:45

Atomic groups and possessive quantifiers

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by PyCon AUReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • An atomic group (?>...) matches once and then refuses to give anything back. A possessive quantifier such as a++ is the same idea attached to one repeat.
  • They remove backtracking on purpose, so they can change what a pattern matches: ^a*+a$ never matches aaa, while ^a*a$ does.
  • PCRE, Perl, Java and Ruby accept both syntaxes. JavaScript rejects both. Python 3.9 rejects them too, and a video description says 3.11 added them.
  • In JavaScript, (?=(a+))\1 emulates an atomic a+: a lookahead is atomic, and the backreference replays what it captured.
  • The emulation adds a capture group, so later group numbers shift. Prefer a named group, and remember that atomic is a promise you make about your data.

Making the engine commit

The last lesson ended with a pattern that takes minutes because the engine, after a failure, reconsiders every earlier choice. But sometimes you know a choice can never be improved by reconsidering it. If a+ has swallowed a run of letters, no shorter run will help the next part of the pattern. Backtracking into it is wasted work, and in a bad pattern it is the entire cost.

An atomic group, written (?>...), says: match this once, as a single indivisible step, and if anything later fails, do not come back and try other ways of matching inside it. A possessive quantifier, written by adding a + after a quantifier (a++, a*+, a?+), is the same promise on one repeat. a*+ means (?>a*). Think of a checkout lane: once you have been rung up for the whole basket you cannot hand items back one by one.

It changes what matches

This is not only an optimisation. It can change the answer. I ran ^a*a$ on aaa in several tools. The ordinary version has to back off one a to let the final a match:

              ^a*a$      ^(?>a*)a$    ^a*+a$
Perl 5.34     match      no match     no match
pcre2grep     match      no match     no match
Java 21       match      no match     no match
Ruby 2.6      match      no match     no match

The atomic and possessive versions take all three as, are never allowed to return one, and fail. If you intended “any number of a’s, then one more a”, the possessive version is wrong. Use these only where the repeated part cannot compete with what follows it.

Using them to fix a blow-up

Last lesson, ^(a+)+$ on forty as and a ! made pcre2grep give up with its match-limit error. Both of these ran instantly in the same tool:

^(?>a+)+$      (no match, instantly)
^(a++)+$       (no match, instantly)

I also ran both in Perl on 5,000 as and a !, and got “no match” without delay. Java accepted (a++)+ on 40 as and answered in 0.23 ms. The atomic group stops the engine from re-splitting the run, so the one failing attempt is all there is.

What your flavour accepts

JavaScript   (?>a+)  ->  SyntaxError: Invalid group
             a++     ->  SyntaxError: Nothing to repeat
Python 3.9   (?>a+)  ->  error: unknown extension ?>
             a++     ->  error: multiple repeat

PCRE, Perl, Java and Ruby accepted both in my runs. Python is the version-sensitive one: re in 3.9 rejects them, and the learnbyexample video description says the re module supports atomic grouping and possessive quantifiers from Python 3.11. I do not have 3.11 on this machine, so I did not run that. Before 3.11 the third-party regex module was the route, which was also not installed here.

The JavaScript emulation

JavaScript has no atomic syntax, but its lookahead is atomic: once (?=...) has matched, the engine does not backtrack into it. Combine that with a backreference and you have the effect. A lookahead matches a+ greedily and captures it, then \1 consumes exactly that text:

/^(?:(?=(a+))\1)+$/   // atomic version of ^(a+)+$

Results from Node 26:

emulated, 30 a's then !       false   0.02 ms
emulated, 5,000 a's then !    false   0.03 ms
emulated, 5,000 a's           true    0.00 ms
plain ^(a+)+$, 30 a's then !  false   50,582 ms (cold first run)

The last line is the plain pattern run cold in a fresh process, which is slower than the warm 4.7 seconds in the previous lesson, for reasons given there. The emulation also gets the semantics right. Plain /a+ab/ on aaab returned aaab after backing off. The emulated atomic /(?=(a+))\1ab/ returned null, matching the PCRE behaviour above.

There is a cost. The trick adds a capture group. In /(?=(a+))\1(b)/ on aab, group 1 is aa and the b you wanted is group 2. Insert one of these into an existing pattern and every later group number shifts. A named group avoids this, and /^(?:(?=(?<run>a+))\k<run>)+$/ ran in 0.02 ms on the failing input. It is also harder to read than (?>a+), so add a comment saying what it is.

About the video

“Faster, Faster! Improving regex performance with atomic grouping, possessive quantifiers and more!” is a PyCon AU 2023 talk by Peter Lovett, published 23 August 2023, 29 minutes 54 seconds. The description says it is not an introduction to regex and assumes Python. The chapters include “Backtracking mechanics” and “Atomic and possessive tools”, and I clipped to the span from the first to just before the summary. I couldn’t read a transcript, so I can’t say which flavours it names or whether it covers the lookahead emulation, which I doubt for a Python talk. A correction in the description concerns the cache size, not this section. English per its title and description.

What I did not run

Python 3.11 or newer, the Python regex module, .NET, and RE2 (which has neither feature). I did not benchmark atomic groups against the plain forms on realistic text.

Next

Rewriting patterns is one defence. Choosing an engine that cannot backtrack is the other, and it forces a trade: regular languages and linear-time engines.

Check yourself

  1. 01What does ^a*+a$ do on 'aaa', and why?

    It fails. The possessive a*+ takes all three a's and will not give one back, so the final a has nothing left to match. The ordinary ^a*a$ backs off one a and matches.

  2. 02Why is ^(?>a+)+$ safe on 'aaa...a!' when ^(a+)+$ is not?

    Once the atomic group has taken a run of a's it never revisits how that run could be split. The engine fails after one attempt instead of trying every split. I ran it on 40 a's and a !, and PCRE2 answered instantly.

  3. 03How do you write an atomic a+ in JavaScript, and what does it cost?

    (?=(a+))\1. The lookahead matches a+ and cannot be backtracked into, and \1 consumes the captured text. The cost is an extra capture group that shifts the numbering of later groups, which a named group avoids.

  4. 04When would making a quantifier possessive be a bug?

    When the text it consumed is needed by something later. For example a*+a can never succeed. Use possessive and atomic only where the greedy part cannot overlap what follows.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark