Python re 模块,_expand() 实例源码

我们从Python开源项目中,提取了以下3个代码示例,用于说明如何使用re._expand()

项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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)
项目:PythonSed    作者:GillesArcas    | 项目源码 | 文件源码
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 --------------------------------------------------------------------