微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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)
项目: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, replacement)
                else:
                    return matchobj.group(0)

    try:
        if compiled is None:
            string_res, nsubst = re.subn(pattern, Nth(), flags)
        else:
            string_res, nsubst = compiled.subn(Nth(), 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 --------------------------------------------------------------------

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐