Skip to content

Instantly share code, notes, and snippets.

@patarapolw
Created November 18, 2018 07:14
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 patarapolw/8617919f0f83cb4df285cf8bf06dd2d6 to your computer and use it in GitHub Desktop.
Save patarapolw/8617919f0f83cb4df285cf8bf06dd2d6 to your computer and use it in GitHub Desktop.
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