Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. from pyparsing import (
  2. Literal,
  3. ZeroOrMore,
  4. Forward,
  5. stringStart,
  6. stringEnd,
  7. )
  8.  
  9. def disable(item, elem):
  10. """Prevent elem from matching inside of item."""
  11. return item # what to do here?
  12.  
  13. atom = Literal("a")
  14.  
  15. op1 = Literal("*")
  16. op2 = Literal("+")
  17.  
  18. no1open = Literal("(")
  19. no1close = Literal(")")
  20.  
  21. expr = Forward()
  22.  
  23. expr0 = atom | no1open + disable(expr, op1) + no1close
  24. expr1 = expr0 + ZeroOrMore(op1 + expr0)
  25. expr <<= expr1 + ZeroOrMore(op2 + expr1)
  26.  
  27. grammar = stringStart + expr + stringEnd
  28.  
  29. def match_in(text):
  30. """Determines if there is a match for grammar in text."""
  31. for result in grammar.parseWithTabs().scanString(text):
  32. return True
  33. return False
  34.  
  35. assert match_in("a * a")
  36. assert match_in("a + a")
  37. assert match_in("a * a + a * a")
  38. assert match_in("a + (a + a)")
  39. assert match_in("a * (a + a)")
  40. assert not match_in("a + (a * a)") # fails, because disable does nothing
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement