Commit b67a25c0 authored by Barry Warsaw's avatar Barry Warsaw

Store the current regex syntax along with the regular expression

string as the key to the cache.  This means that changing the syntax
will return the correct compiled pattern.

clear_cache(): New function.
parent 909d7c32
...@@ -109,27 +109,32 @@ def capwords(str, pat='[^a-zA-Z0-9_]+'): ...@@ -109,27 +109,32 @@ def capwords(str, pat='[^a-zA-Z0-9_]+'):
# Manage a cache of compiled regular expressions. # Manage a cache of compiled regular expressions.
# If the pattern is a string a compiled version of it is returned. #
# If the pattern has been used before we return an already compiled # If the pattern is a string a compiled version of it is returned. If
# the pattern has been used before we return an already compiled
# version from the cache; otherwise we compile it now and save the # version from the cache; otherwise we compile it now and save the
# compiled version in the cache. # compiled version in the cache, along with the syntax it was compiled
# Instead of a string, a compiled regular expression can also be # with. Instead of a string, a compiled regular expression can also
# passed. # be passed.
# WARNING: if the pattern syntax is changed, the cache should be
# flushed!
cache = {} cache = {}
def compile(pat): def compile(pat):
if type(pat) <> type(''): if type(pat) <> type(''):
return pat # Assume it is a compiled regex return pat # Assume it is a compiled regex
if cache.has_key(pat): key = (pat, regex.get_syntax())
prog = cache[pat] # Get it from the cache if cache.has_key(key):
prog = cache[key] # Get it from the cache
else: else:
prog = cache[pat] = regex.compile(pat) prog = cache[key] = regex.compile(pat)
return prog return prog
def clear_cache():
global cache
cache = {}
# Expand \digit in the replacement. # Expand \digit in the replacement.
# Each occurrence of \digit is replaced by the substring of str # Each occurrence of \digit is replaced by the substring of str
# indicated by regs[digit]. To include a literal \ in the # indicated by regs[digit]. To include a literal \ in the
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment