Compiling regex inside function?

alex23 wuwei23 at gmail.com
Mon Aug 3 18:56:02 CEST 2009


Anthra Norell <anthra.nor... at bluewin.ch> wrote:
> def entries (l):
>         r = re.compile ('([0-9]+) entr(y|ies)')
>         match = r.search (l)
>         if match: return match.group (1)
>
> So the question is: does "r" get regex-compiled once at py-compile time
> or repeatedly at entries() run time?

The docs say:
The compiled versions of the most recent patterns passed to re.match
(), re.search() or re.compile() are cached, so programs that use only
a few regular expressions at a time needn’t worry about compiling
regular expressions.

(But they don't say how few is 'only a few'...)

If you're concerned about it, you could always set the compiled
pattern to a default value in the function's argspec, as that _is_
only executed the once:

def entries(line, regex = re.compile('([0-9]+) entr(y|ies)'):
    match = regex.search(line)
    ...



More information about the Python-list mailing list