any chance regular expressions are cached?

Tim Chase python.list at tim.thechases.com
Mon Mar 10 01:52:50 CET 2008


>     s=re.sub(r'\n','\n'+spaces,s)
>     s=re.sub(r'^',spaces,s)
>     s=re.sub(r' *\n','\n',s)
>     s=re.sub(r' *$','',s)
>     s=re.sub(r'\n*$','',s)
> 
> Is there any chance that these will be cached somewhere, and save
> me the trouble of having to declare some global re's if I don't
> want to have them recompiled on each function invocation?


 >>> import this
...
Explicit is better than implicit
...


Sounds like what you want is to use the compile() call to compile 
once, and then use the resulting objects:

   re1 = re.compile(r'\n')
   re2 = re.compile(r'^')
   ...
   s = re1.sub('\n' + spaces, s)
   s = re2.sub(spaces, s)
   ...


The compile() should be done once (outside loops, possibly at a 
module level, as, in a way, they're constants) and then you can 
use the resulting object without the overhead of compiling.

-tkc






More information about the Python-list mailing list