Optimization recommendations
In the following sections, we will find a number of recommendations that could be applied to improve regular expressions.
The best tool will always be common sense, and common sense will need to be used even while following these recommendations. It has to be understood when the recommendation is applicable and when it is not. For instance, the recommendation don't be greedy cannot be used in all the cases.
Reuse compiled patterns
We have learned in Chapter 2, Regular Expressions with Python, that to use a regular expression we have to convert it from its string representation to a compiled form as RegexObject
.
This compilation takes some time. If we are using the rest of the module operations instead of using the compile function to avoid the creation of the RegexObject
, we should understand that the compilation is executed anyway and a number of compiled RegexObject
are cached automatically.
However, when we are compiling, that cache won't back us. Every single...