any chance regular expressions are cached?

John Machin sjmachin at lexicon.net
Mon Mar 10 05:42:49 CET 2008


On Mar 10, 11:42 am, m... at pixar.com wrote:
> I've got a bit of code in a function like this:
>
>     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?
>

Yes they will be cached. But do yourself a favour and check out the
string methods.

E.g.
>>> import re
>>> def opfunc(s, spaces):
...     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)
...     return s
...
>>> def myfunc(s, spaces):
...     return '\n'.join(spaces + x.rstrip() if x.rstrip() else '' for
x in s.splitlines())
...
>>> t1 = 'foo\nbar\nzot\n'
>>> t2 = 'foo\nbar     \nzot\n'
>>> t3 = 'foo\n\nzot\n'
>>> [opfunc(s, '   ') for s in (t1, t2, t3)]
['   foo\n   bar\n   zot', '   foo\n   bar\n   zot', '   foo\n\n
zot']
>>> [myfunc(s, '   ') for s in (t1, t2, t3)]
['   foo\n   bar\n   zot', '   foo\n   bar\n   zot', '   foo\n\n
zot']
>>>



More information about the Python-list mailing list