4

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.

Filip Haglund
  • 13,919
  • 13
  • 64
  • 113

1 Answers1

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.)

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125