Created
November 29, 2011 06:46
-
-
Save aita/1403744 to your computer and use it in GitHub Desktop.
pattern query
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
from django.utils import tree | |
PATTERN_DICT = { | |
"ALPHABET": r"a-zA-Z", | |
"NUMBER": r"0-9", | |
} | |
class S(tree.Node): | |
""" | |
""" | |
# Connection types | |
AND = 'AND' | |
#OR = 'OR' | |
default = AND | |
def __init__(self, *args, **kwargs): | |
super(S, self).__init__(children=list(args) + kwargs.items()) | |
def _combine(self, other, conn): | |
if not isinstance(other, S): | |
raise TypeError(other) | |
obj = type(self)() | |
obj.add(self, conn) | |
obj.add(other, conn) | |
return obj | |
def __or__(self, other): | |
return self._combine(other, self.AND) | |
def __and__(self, other): | |
return self._combine(other, self.AND) | |
ALPHABET = S("ALPHABET") | |
NUMBER = S("NUMBER") | |
def regex_from_S(s): | |
""" | |
>>> regex_from_S(ALPHABET) | |
'[a-z-A-Z]+' | |
>>> regex_from_S(ALPHABET&NUMBER) | |
'[a-z-A-Z0-9]+' | |
""" | |
if isinstance(s, S): | |
if s.connector == "AND": | |
return "[%s]+" % (r"".join([regex_from_S(c) for c in s.children]),) | |
else: | |
raise ValueError | |
elif isinstance(s, basestring): | |
return PATTERN_DICT[s] | |
else: | |
raise TypeError | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment