Reputation: 1319
s = '>50&<100'
s2 = '>30'
s3 = '<30'
s4 = '=10'
s5 = '!=10'
s6 = '>2|<5'
so my strings should be:
comparison operator ( < > = != ) followed by an integer value -> we call it EXPRESSION
optional logical operator ( | & ) followed by an EXPRESSION
What's the best way to:
a. validate the input string b parse it so I can create the expression in valid python
P.S I can thing of a regex solution. I was thinking something like creating a grammar and parse it to a tree.
Upvotes: 0
Views: 322
Reputation: 107287
you can create you regex
by following , and as says in comment if you want a common solution you need this patterns :
s = '>\d+&<\d+'
s2 = '>\d+'
s3 = '<\d+'
s4 = '=\d+'
s5 = '!=\d+'
s6 = '>\d+|<\d+'
string_list=[s,s2,s3,s4,s5,s6]
rx = re.compile('|'.join(map(re.escape, string_list)))
and then use a proper re
function (for example : rx.match(string)
)!
re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
Upvotes: 1
Reputation: 26667
How about the regex
^(<|>|!=|=)\d+([&|](<|>|!=|=)\d+)*
Example : http://regex101.com/r/fX5lC2/2
Upvotes: 1