Skip to content

Instantly share code, notes, and snippets.

@thomasballinger
Created October 4, 2012 20:18
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 thomasballinger/3836154 to your computer and use it in GitHub Desktop.
Save thomasballinger/3836154 to your computer and use it in GitHub Desktop.
functional regex engine in python by psykotic of reddit
from itertools import chain
def nil(s):
yield s
def seq(l, r):
return lambda s: (sr for sl in l(s) for sr in r(sl))
def alt(l, r):
return lambda s: chain(l(s), r(s))
def star(e):
return lambda s: chain(nil(s), seq(e, star(e))(s))
def plus(e):
return seq(e, star(e))
def char(c):
def match(s):
if s and s[0] == c: yield s[1:]
return match
# c(a|d)+
re = seq(char('c'), seq(plus(alt(char('a'), char('d'))), char('r')))
import sys
s = sys.stdin.readline()[:-1]
for r in e(s): print "Match with remainder:", r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment