Created
September 29, 2016 20:07
-
-
Save bmwant/f9c3dbd5d2c69dd1f7cc7f1551a5ff4b to your computer and use it in GitHub Desktop.
Regex #1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import term | |
exp = '(+|-|e)dd*' | |
class InvalidInput(ValueError): | |
pass | |
class Matcher(object): | |
def __init__(self, text): | |
self.pos = 0 | |
self.text = text | |
def match(self): | |
cursor = self.read() | |
try: | |
ch = next(cursor) | |
if ch == '+' or ch == '-': | |
ch = next(cursor) | |
if ch.isdigit(): | |
while True: | |
try: | |
ch = next(cursor) | |
except StopIteration: | |
break | |
if not ch.isdigit(): | |
self.error('Number should contain only digits') | |
else: | |
self.error('Number should start with a digit') | |
except StopIteration: | |
self.error('Unexpected end of input') | |
def read(self): | |
for pos, char in enumerate(self.text): | |
self.pos = pos | |
yield char | |
def error(self, message): | |
term.writeLine('Error at position {pos}: {message}'.format( | |
pos=self.pos, message=message), term.red) | |
term.writeLine(self.text) | |
term.write('-'*self.pos, term.yellow) | |
term.write('^\n', term.yellow) | |
raise InvalidInput(message) | |
def main(): | |
valid_input = '-234532' | |
invalid_input = '+235235d323' | |
m1 = Matcher(valid_input) | |
m1.match() | |
m2 = Matcher(invalid_input) | |
m2.match() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment