sed.py 文件源码

python
阅读 26 收藏 0 点赞 0 评论 0

项目: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 --------------------------------------------------------------------
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号