Created
November 18, 2018 07:14
-
-
Save patarapolw/8617919f0f83cb4df285cf8bf06dd2d6 to your computer and use it in GitHub Desktop.
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 lark | |
parser = lark.Lark(r''' | |
?atom : atom or atom | |
| atom and atom | |
| "(" atom ")" | |
| compare | |
| value | |
compare : value ":" value | |
| value "=" value | |
| value ">" value | |
| value ">=" value | |
| value "<" value | |
| value "<=" value | |
| "-" value | |
and : "&" | " " | |
or.1 : "|" | / or /i | |
value : /\w+/i | |
| ESCAPED_STRING | |
%import common.ESCAPED_STRING | |
''', start='atom') | |
def parse(q): | |
try: | |
return parser.parse(q.strip()) | |
except lark.exceptions.UnexpectedCharacters: | |
return None | |
if __name__ == '__main__': | |
""" | |
value a | |
compare | |
value a | |
value b | |
None | |
atom | |
compare | |
value a | |
value b | |
and | |
compare | |
value c | |
value d | |
compare | |
value "a:b" | |
value c | |
compare | |
value "a b" | |
value c | |
compare | |
value a | |
value "b:c" | |
atom | |
compare | |
value a | |
value b | |
or OR | |
compare | |
value c | |
value d | |
atom | |
compare | |
value a | |
value b | |
or OR | |
compare | |
value c | |
value d | |
""" | |
for q in [ | |
'a', | |
'a:b', | |
'a:b:c', | |
'a:b c:d', | |
'"a:b":c', | |
'"a b":c', | |
'a:"b:c"', | |
'(a:b) OR c:d', | |
'a:b OR (c:d)' | |
]: | |
print(getattr(parse(q), 'pretty', lambda: None)()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment