Skip to content
Advertisement

Do Python regular expressions have an equivalent to Ruby’s atomic grouping?

Ruby’s regular expressions have a feature called atomic grouping (?>regexp), described here, is there any equivalent in Python’s re module?

Advertisement

Answer

Python does not directly support this feature, but you can emulate it by using a zero-width lookahead assert ((?=RE)), which matches from the current point with the same semantics you want, putting a named group ((?P<name>RE)) inside the lookahead, and then using a named backreference ((?P=name)) to match exactly whatever the zero-width assertion matched. Combined together, this gives you the same semantics, at the cost of creating an additional matching group, and a lot of syntax.

For example, the link you provided gives the Ruby example of

JavaScript

We can emulate that in Python as such:

JavaScript

We can show that I’m doing something useful and not just spewing line noise, because if we change it so that the inner group doesn’t eat the final ", it still matches:

JavaScript

You can also use anonymous groups and numeric backreferences, but this gets awfully full of line-noise:

JavaScript

(Full disclosure: I learned this trick from perl’s perlre documentation, which mentions it under the documentation for (?>...).)

In addition to having the right semantics, this also has the appropriate performance properties. If we port an example out of perlre:

JavaScript

We see a dramatic improvement:

JavaScript

Which only gets more dramatic as we extend the length of the search string.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement