9be401
#! /usr/bin/env python3
9be401
9be401
from __future__ import print_function
9be401
9be401
import re
9be401
9be401
try:
9be401
    basestring
9be401
except NameError:
9be401
    basestring = str
9be401
9be401
# ---------------------------------------------------------- Regex Match()
9be401
# beware, stupid python interprets backslashes in replace-parts only partially!
9be401
class MatchReplace:
9be401
    """ A MatchReplace is a mix of a Python Pattern and a Replace-Template """
9be401
    def __init__(self, matching, template, count = 0, flags = None):
9be401
        """ setup a substition from regex 'matching' into 'template',
9be401
            the replacement count default of 0 will replace all occurrences.
9be401
            The first argument may be a Match object or it is a string that
9be401
            will be turned into one by using Match(matching, flags). """
9be401
        self.template = template
9be401
        MatchReplace.__call__(self, matching, template, count, flags)
9be401
    def __call__(self, matching, template = None, count = 0, flags = None):
9be401
        """ other than __init__ the template may be left off to be unchanged"""
9be401
        if isinstance(count, basestring): # count/flags swapped over?
9be401
            flags = count; count = 0
9be401
        if isinstance(matching, Match):
9be401
            self.matching = matching
9be401
        else:
9be401
            self.matching = Match()(matching, flags) ## python 2.4.2 bug
9be401
        if template is not None:
9be401
            self.template = template
9be401
        self.count = count
9be401
    def __and__(self, string):
9be401
        """ z = MatchReplace('foo', 'bar') & 'foo'; assert z = 'bar' """
9be401
        text, self.matching.replaced = \
9be401
              self.matching.regex.subn(self.template, string, self.count)
9be401
        return text
9be401
    def __rand__(self, string):
9be401
        """ z = 'foo' & Match('foo') >> 'bar'; assert z = 'bar' """
9be401
        text, self.matching.replaced = \
9be401
              self.matching.regex.subn(self.template, string, self.count)
9be401
        return text
9be401
    def __iand__(self, string):
9be401
        """ x = 'foo' ; x &= Match('foo') >> 'bar'; assert x == 'bar' """
9be401
        string, self.matching.replaced = \
9be401
                self.matching.regex.subn(self.template, string, self.count)
9be401
        return string
9be401
    def __rshift__(self, count):
9be401
        " shorthand to set the replacement count: Match('foo') >> 'bar' >> 1 "
9be401
        self.count = count ; return self
9be401
    def __rlshift__(self, count):
9be401
        self.count = count ; return self
9be401
9be401
class Match:
9be401
    """ A Match is actually a mix of a Python Pattern and MatchObject """
9be401
    def __init__(self, pattern = None, flags = None):
9be401
        """ flags is a string: 'i' for case-insensitive etc.; it is just
9be401
        short for a regex prefix: Match('foo','i') == Match('(?i)foo') """
9be401
        Match.__call__(self, pattern, flags)
9be401
    def __call__(self, pattern, flags = None):
9be401
        assert isinstance(pattern, str) or pattern is None
9be401
        assert isinstance(flags, str) or flags is None
9be401
        self.replaced = 0 # set by subn() inside MatchReplace
9be401
        self.found = None # set by search() to a MatchObject
9be401
        self.pattern = pattern
9be401
        if pattern is not None:
9be401
            if flags:
9be401
                self.regex = re.compile("(?"+flags+")"+self.pattern)
9be401
            else:
9be401
                self.regex = re.compile(self.pattern)
9be401
        return self
9be401
    def __repr__(self):
9be401
        return self.pattern
9be401
    def __truth__(self):
9be401
        return self.found is not None
9be401
    def __and__(self, string):
9be401
        self.found = self.regex.search(string)
9be401
        return self.__truth__()
9be401
    def __rand__(self, string):
9be401
        self.found = self.regex.search(string)
9be401
        return self.__truth__()
9be401
    def __rshift__(self, template):
9be401
        return MatchReplace(self, template)
9be401
    def __rlshift__(self, template):
9be401
        return MatchReplace(self, template)
9be401
    def __getitem__(self, index):
9be401
        return self.group(index)
9be401
    def group(self, index):
9be401
        assert self.found is not None
9be401
        return self.found.group(index)
9be401
    def finditer(self, string):
9be401
        return self.regex.finditer(string)
9be401
9be401
if __name__ == "__main__":
9be401
    # matching:
9be401
    if "foo" & Match("oo"):
9be401
        print("oo")
9be401
    x = Match()
9be401
    if "foo" & x("(o+)"):
9be401
        print(x[1])
9be401
    # replacing:
9be401
    y = "fooboo" & Match("oo") >> "ee"
9be401
    print(y)
9be401
    r = Match("oo") >> "ee"
9be401
    print("fooboo" & r)
9be401
    s = MatchReplace("oo", "ee")
9be401
    print("fooboo" & s)