def compile_replace(pattern, repl, flags=0):
"""Construct a method that can be used as a replace method for `sub`, `subn`, etc."""
call = None
if pattern is not None and isinstance(pattern, RE_TYPE):
if isinstance(repl, (compat.string_type, compat.binary_type)):
repl = ReplaceTemplate(pattern, repl, bool(flags & FORMAT))
call = Replace(
functools.partial(_apply_replace_backrefs, repl=repl), repl.use_format, repl.pattern_hash
)
elif isinstance(repl, Replace):
if flags:
raise ValueError("Cannot process flags argument with a compiled pattern!")
if repl.pattern_hash != hash(pattern):
raise ValueError("Pattern hash doesn't match hash in compiled replace!")
call = repl
elif isinstance(repl, ReplaceTemplate):
if flags:
raise ValueError("Cannot process flags argument with a ReplaceTemplate!")
call = Replace(
functools.partial(_apply_replace_backrefs, repl=repl), repl.use_format, repl.pattern_hash
)
else:
raise TypeError("Not a valid type!")
else:
raise TypeError("Pattern must be a compiled regular expression!")
return call
# Convenience methods like re has, but slower due to overhead on each call.
# It is recommended to use compile_search and compile_replace
评论列表
文章目录