Ruby’s regular expressions have a feature called atomic grouping (?>regexp), described here, is there any equivalent in Python’s re module?
Ruby’s regular expressions have a feature called atomic grouping (?>regexp) , described here ,
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
We can emulate that in Python as such:
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:You can also use anonymous groups and numeric backreferences, but this gets awfully full of line-noise:
(Full disclosure: I learned this trick from perl’s
perlredocumentation, 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:We see a dramatic improvement:
Which only gets more dramatic as we extend the length of the search string.