# 2 engines: NFA/DFA RegEx-Art # FA -> Finite Automation class Regex: """ Can only support a-z """ def __init__(self): self.fsm = [] def _char_to_int(self, char): """ Returns 0 for a, 1 for b, 2 for c, ... 25 for z """ return ord(char) - 97 def compile(self, regex_string): self.fsm = [] for char in regex_string: next_valid_state = len(self.fsm) + 1 if char == ".": state = [next_valid_state] * 26 else: state = [0] * 26 state[self._char_to_int(char)] = next_valid_state self.fsm.append(state) def match(self, text): current_state = 0 for input_char in text: current_state = self.fsm[current_state][self._char_to_int(input_char)] if current_state == 0: return False return True def __str__(self): result = "" for row in zip(*self.fsm): result += " ".join(str(x) for x in row) + "\n" return result