gosom
gosom

Reputation: 1319

python parse string with rules

s = '>50&<100'
s2 = '>30'
s3 = '<30'
s4 = '=10'
s5 = '!=10'
s6 = '>2|<5'

so my strings should be:

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

Answers (2)

Kasravnd
Kasravnd

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

nu11p01n73R
nu11p01n73R

Reputation: 26667

How about the regex

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

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

Upvotes: 1

Related Questions