0
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.

2 Answers 2

1

How about the regex

^(<|>|!=|=)\d+([&|](<|>|!=|=)\d+)*

Example : http://regex101.com/r/fX5lC2/2

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Wont this only match the exact examples he gave, rather than applying the generic rules he wants to use?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.