Is it worth using Python's re.compile?

前端 未结 26 2203
旧时难觅i
旧时难觅i 2020-11-22 12:51

Is there any benefit in using compile for regular expressions in Python?

h = re.compile(\'hello\')
h.match(\'hello world\')

vs



        
26条回答
  •  无人共我
    2020-11-22 13:17

    (months later) it's easy to add your own cache around re.match, or anything else for that matter --

    """ Re.py: Re.match = re.match + cache  
        efficiency: re.py does this already (but what's _MAXCACHE ?)
        readability, inline / separate: matter of taste
    """
    
    import re
    
    cache = {}
    _re_type = type( re.compile( "" ))
    
    def match( pattern, str, *opt ):
        """ Re.match = re.match + cache re.compile( pattern ) 
        """
        if type(pattern) == _re_type:
            cpat = pattern
        elif pattern in cache:
            cpat = cache[pattern]
        else:
            cpat = cache[pattern] = re.compile( pattern, *opt )
        return cpat.match( str )
    
    # def search ...
    

    A wibni, wouldn't it be nice if: cachehint( size= ), cacheinfo() -> size, hits, nclear ...

提交回复
热议问题