Are atomic groups taking up more memory than necessary?

Create issue
Issue #309 resolved
Former user created an issue

I've noticed that the following regex: r'<!--(?>[^-]++|-(?!->))*+-->' (which is supposed to do the same job as the old good comment regex: r'<!--[\s\S]*?-->') ends up with a MemoryError when there is a very long comment in the string.

regex.findall(r'<!--(?>[^-]++|-(?!->))*-->', paste())
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "...\Python37\lib\site-packages\", line 333, in findall
    overlapped, concurrent)

Why is that happening? Since all the groups in the regex are atomic ones, the engine only needs to remember the last successful matching position before each atomic group and proceed towards the end as soon as each group fails. That shouldn't require that much memory, should it?

Now I know that what I just said is a gross simplification of what is actually happening under the hood and I might be wrong about it, but I thought maybe there is something that can be improved so I decided to create this issue.

Here is a sample text you can download:

Comments (4)

  1. Matthew Barnett repo owner

    You have 2 slightly different regexes there. In the first paragraph you have (?>...)*+ (possessive), whereas in the trackback you have (?>...)* (greedy).

    The memory problem is more to do with the repeat than the atomic group.



    is basically the same as this:


    It behaves like a greedy repeat, remembering the state for each iteration, until it can match the repeated part no more. Only then does it leave the outer atomic group and discard the accumulated backtracking information.

    You can see this more clearly with:

    >>> print('(aa|a){2}+', 'aa'))
    <regex.Match object; span=(0, 2), match='aa'>
    >>>'(aa|a){2}+', 'aa').groups()
    >>> print('(?>(aa|a)){2}+', 'aa'))
    >>> None

    I'll try to look for ways of reducing the memory usage.

  2. 40a

    Thanks, Matthew! It worked. Yet I came up with a similar issue with possessive groups:

    >>>'<!--([^-]*(-(?!->))*)*+-->', paste())  # successful match
    >>> # Change the two greedy quantifiers into possessive ones:
    >>>'<!--([^-]*+(-(?!->))*+)*+-->', paste())
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
      File "...\Python\Python37\lib\site-packages\", line 266, in search
        concurrent, partial)
  3. Log in to comment