Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from pyparsing import (
- Literal,
- ZeroOrMore,
- Forward,
- stringStart,
- stringEnd,
- )
- def disable(item, elem):
- """Prevent elem from matching inside of item."""
- return item # what to do here?
- atom = Literal("a")
- op1 = Literal("*")
- op2 = Literal("+")
- no1open = Literal("(")
- no1close = Literal(")")
- expr = Forward()
- expr0 = atom | no1open + disable(expr, op1) + no1close
- expr1 = expr0 + ZeroOrMore(op1 + expr0)
- expr <<= expr1 + ZeroOrMore(op2 + expr1)
- grammar = stringStart + expr + stringEnd
- def match_in(text):
- """Determines if there is a match for grammar in text."""
- for result in grammar.parseWithTabs().scanString(text):
- return True
- return False
- assert match_in("a * a")
- assert match_in("a + a")
- assert match_in("a * a + a * a")
- assert match_in("a + (a + a)")
- assert match_in("a * (a + a)")
- assert not match_in("a + (a * a)") # fails, because disable does nothing
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement