我们从Python开源项目中,提取了以下3个代码示例,用于说明如何使用re._expand()。
def expand(self, template): """Return the string obtained by doing backslash substitution and resolving group references on template.""" import sre return sre._expand(self.re, self, template)
def re_sub_ex(pattern, compiled, replacement, string, count, flags): # re.sub() extended: # - an unmatched group returns an empty string rather than None # (http://gromgull.net/blog/2012/10/python-regex-unicode-and-brokenness/) # - the nth occurrence is replaced rather than the nth first ones # (https://mail.python.org/pipermail/python-list/2008-December/475132.html) class Match(): def __init__(self, m): self.m = m self.string = m.string def group(self, n): return self.m.group(n) or '' class Nth(object): def __init__(self): self.calls = 0 def __call__(self, matchobj): if count == 0: return re._expand(pattern, Match(matchobj), replacement) else: self.calls += 1 if self.calls == count: return re._expand(pattern, Match(matchobj), replacement) else: return matchobj.group(0) try: if compiled is None: string_res, nsubst = re.subn(pattern, Nth(), string, count, flags) else: string_res, nsubst = compiled.subn(Nth(), string, count) except re.error as e: raise SedException('regexp: %s' % e.message) except: raise # nsubst is the number of subst which would have been made without # the redefinition if count == 0: return (nsubst > 0), string_res else: return (nsubst >= count), string_res # -- Main --------------------------------------------------------------------