User provides a string containing a Python expression : "a==(1,1) and {b==2 or c==foo}"
.
I am trying to write a parser that checks the following rules:
- There needs to be a whitespace before and after a logical expression (
or
orand
) - There needs to be a whitespace before and after curly braces
- There should be NO whitespace within an expression (
a ==(1,1)
is invalid)
I found that "parser" module but I am not sure I understand it.
Establishing all the rules through multiple regular expressions (reading the string char by char and making sure if satisfies the rules) is very tedious.
What is the most elegant way to tackle this 开发者_开发知识库problem?
The most elegant way I'd say is to use something like pyparsing, a real parser combined with "pythonic" ease of use.
It may be a bit of overkill for small projects, but it isn't too hard to get started and will allow for plenty of growth in the syntax. Software requirements always seem to grow in one direction so I'd recommend giving it a try.
精彩评论