Created
March 30, 2017 05:39
-
-
Save nitely/01883196c0a89c9b49dd65d66b920a92 to your computer and use it in GitHub Desktop.
Python re.Scanner (almost) without using internals
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 sre_compile | |
import re | |
class Scanner: | |
def __init__(self, rules, flags=0): | |
self.scanner = sre_compile.compile( | |
'(%s)' % '|'.join('(%s)' % pattern for pattern in rules), | |
flags) | |
def scan(self, string): | |
result = [] | |
append = result.append | |
match = self.scanner.scanner(string).match | |
i = 0 | |
while True: | |
m = match() | |
if not m: | |
break | |
j = m.end() | |
if i == j: | |
break | |
action = self.lexicon[m.lastindex-1][1] | |
if callable(action): | |
self.match = m | |
action = action(self, m.group()) | |
if action is not None: | |
append(action) | |
i = j | |
return result, string[i:] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment