Can you pre-compile regular expressions in Python, save them to a file, and then reload them from the file?

Viewed 194

I have an application that loads a large table of regular expressions from an Excel file, compiles them, and then uses them to perform its function. It takes about 2 minutes for Python to compile the regular expressions, which will increase as I add more expressions to the Excel file. The Excel file does not change often, so I would like to avoid the two-minute+ startup time whenever the Excel file has not changed.

Is there a way to cache the compiled regular expressions to a file that I can load when the Excel file hasn't changed?

1 Answers

You can store the compiled regular expressions in pickle files:

import re
import pickle

r1 = re.compile('\d\d\d')

with open('tmp', 'wb') as fh:
    pickle.dump(r1, fh)


with open('tmp', 'rb') as fh:
    r2 = pickle.load(fh)

    print(r2.match('673'))

<re.Match object; span=(0, 3), match='673'>

Related