Created
January 12, 2016 00:57
-
-
Save thepaul/ceccdd458c77dad301a9 to your computer and use it in GitHub Desktop.
Similar to re.Scanner but works as a coroutine, yielding tokens as found
This file contains hidden or 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 re | |
class NotAToken(Exception): | |
pass | |
class YieldScanner(re.Scanner): | |
def scan(self, inputstr): | |
match = self.scanner.scanner(inputstr).match | |
pos = 0 | |
while True: | |
m = match() | |
if m is None: | |
if pos < len(inputstr): | |
raise NotAToken(inputstr[pos:]) | |
break | |
endpos = m.end() | |
if pos == endpos: | |
raise EmptyToken(inputstr[pos:]) | |
yield (self.lexicon[m.lastindex - 1][1], m) | |
pos = endpos |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment