Is Perl *that* good?

Wilk wilkSPAM at OUTflibuste.net
Tue Apr 27 09:45:02 EDT 2004


Roy Smith <roy at panix.com> writes:

> Ville Vainio <ville at spammers.com> wrote:
>
>> >>>>> "Asun" == Asun Friere <afriere at yahoo.co.uk> writes:
>> 
>>     Asun> Wouldn't you need to import the re module and compile the
>>     Asun> pattern first?  (And wouldn't you use 'search' rather than
>>     Asun> 'match'?)  And
>> 
>> I rarely compile regexps, just pass the string to the re functions.
>
> For the occasional ad-hoc match, this is fine.  The advantage of 
> pre-compiling is that it's faster, since it doesn't have to recompile 
> the regex each time.
>
> I don't see anything in the reference manual which says re.match() 
> caches compilations, but I suspect it does.  Even a trivial check for 
> "thisRegEx is lastRegEx" would be sufficient to negate the speed 
> advantage of pre-compiling in most cases.  Anybody know if it does this?


Looking at the source code of sre.py, it seems that regexp are
auto-cached anyway...

def match(pattern, string, flags=0):
    """Try to apply the pattern at the start of the string, returning
    a match object, or None if no match was found."""
    return _compile(pattern, flags).match(string)

def compile(pattern, flags=0):
    "Compile a regular expression pattern, returning a pattern object."
    return _compile(pattern, flags)

def _compile(*key):
    # internal: compile pattern
    p = _cache.get(key)
    if p is not None:
        return p

I think the advantage of re.compile is just to don't have to repeat the
string everytimes...

-- 
Wilk - http://flibuste.net



More information about the Python-list mailing list