Skip to content

Instantly share code, notes, and snippets.

@latk
Last active June 24, 2018 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save latk/1cd221bf38049a14a1c9064e96daa347 to your computer and use it in GitHub Desktop.
Save latk/1cd221bf38049a14a1c9064e96daa347 to your computer and use it in GitHub Desktop.
A toy regex engine based on backtracking. It is probably buggy. The first variant uses recursion and parsing with derivatives. Due to Python's lack of tail recursion it can only be used for simple regexes. The second variant avoids recursion and makes the backtracking explicit through a stack. It can be extended with more operators.
#!/usr/bin/env python3
"""
A toy regex engine.
Copyright 2018 Lukas Atkinson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
def Sequence(*steps):
steps = list(steps)
if not steps:
return ''
seq = steps.pop()
while len(steps):
seq = _Cons(steps.pop(), seq)
return seq
class _Cons(object):
def __init__(self, left, right):
self.left = left
self.right = right
def __str__(self):
return str(self.left) + str(self.right)
def Choice(*choices):
choices = list(choices)
if not choices:
return ''
choice = choices.pop()
while len(choices):
choice = _Alt(choices.pop(), choice)
return choice
class _Alt(object):
def __init__(self, left, right):
self.left = left
self.right = right
def __str__(self):
return '({}|{})'.format(self.left, self.right)
class Star(object):
def __init__(self, pattern):
self.pattern = pattern
def __str__(self):
return '({})*'.format(self.pattern)
class Maybe(object):
def __init__(self, pattern):
self.pattern = pattern
def __str__(self):
return '({})?'.format(self.pattern)
def match(regex, string, cont=None, depth=0):
"""Match a regex AST against a string.
Returns True if the regex matches at the beginning."""
depth = depth + 1
print("{}match state: {!r} against {}, continue {}".format(
' ' * (depth - 1), string, regex, cont))
if regex is None:
return True
if isinstance(regex, str):
if string.startswith(regex):
return match(cont, string[len(regex):], depth=depth)
return False
if isinstance(regex, _Cons):
return match(regex.left, string,
cont=(_Cons(regex.right, cont) if cont else regex.right),
depth=depth)
if isinstance(regex, _Alt):
if match(regex.left, string, cont=cont, depth=depth):
return True
return match(regex.right, string, cont=cont, depth=depth)
if isinstance(regex, Star):
if match(regex.pattern, string, cont=_Cons(regex, cont), depth=depth):
return True
return match(cont, string, depth=depth)
if isinstance(regex, Maybe):
if match(regex.pattern, string, cont=cont, depth=depth):
return True
return match(cont, string, depth=depth)
assert False, "unknown regex operator"
if __name__ == "__main__":
def check(regex, string, fail=False):
result = match(regex, string)
print(string, result)
if fail:
assert not result
else:
assert result
# (a|b)*c
regex = Sequence(Star(Choice('a', 'b')), 'c')
check(regex, 'abababaca')
check(regex, 'abababa', fail=True)
check(regex, 'cab')
check(regex, 'ababada', fail=True)
regex = Sequence(Star('a'), Star('a'), Star('a'), 'b')
check(regex, 'aaaac', fail=True)
#!/usr/bin/env python3
"""
A toy regex engine.
Copyright 2018 Lukas Atkinson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
class Sequence(object):
def __init__(self, *patterns):
self.patterns = patterns
def __str__(self):
return ''.join(str(pattern) for pattern in self.patterns)
def Choice(*choices):
choices = list(choices)
if not choices:
return Sequence()
choice = choices.pop()
while len(choices):
choice = _Alt(choices.pop(), choice)
return choice
class _Alt(object):
def __init__(self, left, right):
self.left = left
self.right = right
def __str__(self):
return '({}|{})'.format(self.left, self.right)
class Star(object):
def __init__(self, pattern):
self.pattern = pattern
def __str__(self):
return '({})*'.format(self.pattern)
class Maybe(object):
def __init__(self, pattern):
self.pattern = pattern
def __str__(self):
return '({})?'.format(self.pattern)
class Fail(object):
def __str__(self):
return '(*FAIL)'
def match(regex, string):
op_stack = [regex]
backtrack_points = [] # contains (op_stack, string) tuples
# fail if we backtrack into the end of the stack
backtrack_points.append(([Fail()], string))
def save_backtrack_point(alt=None):
saved_op_stack = op_stack[:]
if alt is not None:
saved_op_stack.append(alt)
backtrack_points.append((saved_op_stack, string))
while op_stack:
op = op_stack.pop()
depth = len(backtrack_points)
print("{}match state: {!r} against {}, continue {}".format(
' ' * (depth - 1), string, op, Sequence(*reversed(op_stack))))
if isinstance(op, str):
if string.startswith(op):
string = string[len(op):]
else:
# restore the last backtrack point
op_stack, string = backtrack_points.pop()
elif isinstance(op, Sequence):
op_stack.extend(reversed(op.patterns))
elif isinstance(op, _Alt):
save_backtrack_point(op.right)
op_stack.append(op.left)
elif isinstance(op, Star):
save_backtrack_point()
op_stack.append(op)
op_stack.append(op.pattern)
elif isinstance(op, Maybe):
save_backtrack_point()
op_stack.append(op.pattern)
elif isinstance(op, Fail):
return False
else:
assert False, "unknown regex operator"
return True
if __name__ == "__main__":
def check(regex, string, fail=False):
result = match(regex, string)
print(string, result)
if fail:
assert not result
else:
assert result
# (a|b)*c
regex = Sequence(Star(Choice('a', 'b')), 'c')
check(regex, 'abababaca')
check(regex, 'abababa', fail=True)
check(regex, 'cab')
check(regex, 'ababada', fail=True)
regex = Sequence(Star('a'), Star('a'), Star('a'), 'b')
check(regex, 'aaaac', fail=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment