5

Is there a way to parse regex from right to left in python?

I have a few huge regexes that take about a second to run on my input, for a total run-time of a few minutes. So I tried to test the performance of my regexes, and regexhero had an option to parse regex from right to left, which resulted in about a million times faster execution because of quicker failing.

3

1 Answer 1

12

Yes, the way is to reverse the string (and to write the pattern according to the new string):

string:

'John likes to eat mushrooms'[::-1] 

pattern (what like John?):

r'^(.+) sekil nohJ$'

You can also change the re module to the regex module that provides a reverse search flag (?r):

>>> import regex
>>> regex.findall(r'(?r)\w+(?=\W+\w*e)', 'John likes to eat mushrooms')
['to', 'John']

(Take care of this feature, as .net RightToLeft option, results may be counter-intuitive.)

Sign up to request clarification or add additional context in comments.

5 Comments

So I have to rewrite all my regexes? Doesn't really sound that great.
@mbomb007: no you can't do that. $John likes )+.(^
Right, I always forget about the parentheses.
Why, python regex has not right to left search? It effects the performance.
@keramat: AFAIK, only this module and the .net languages regular expressions have this feature.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.