Skip to content

Instantly share code, notes, and snippets.

@thepaul
Created January 12, 2016 00:57
Show Gist options
  • Save thepaul/ceccdd458c77dad301a9 to your computer and use it in GitHub Desktop.
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
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