import re class Result: def __init__(self, value=[], start=0, end=0): print('INIT:', value) if value == ['a', 'b']: raise self.value = value self.start = start self.end = end class Expression: def __init__(self, regex): self.regex = regex self.pattern = re.compile(self.regex) def match(self, s, offset=0): match = self.pattern.match(s, offset) if match: return Result([match.group(0)], match.start, match.end()) class Group: def __init__(self): self.__children = [] def register(self, el): self.__children.append(el) def match(self, s, offset=0): match = None result = Result() print('!!!',Result().value) result.start = offset result.end = offset for child in self.__children: match = child.match(s, result.end) if not match: return None result.value += match.value result.end = match.end return result class Range: def __init__(self, child, count=1): self.__count = count self.__child = child def match(self, s, offset=0): child = self.__child result = Result([],offset,offset) for i in range(self.__count): print('>>',i) match = child.match(s, result.end) if not match: return None result.end = match.end result.value += match.value return result a = Expression('a') b = Expression('b') g=Group() g.register(a) g.register(b) r = Range(g,2) x = r.match('abab') print(x)