sree
sree

Reputation: 51

How to extract the values after Comparison Operators in string using regex and find if value is object/ str or int/float in python?

I have doubt, SO I have a string ( str ="cars>=30 and jeeps=='one'")Now I want to extract the values after Comparison Operators(In my case the values after >= and == )using re and find whether the value is d-type int or object/string.Is there any way to find this out?

My code:

x = "cars>=20 and jeeps =='one'"
if 'and' in x:
    r=x.split('and')
    l=[]
    for i in r:
        print(i)
        l.append(re.findall(r'([<>]=?|==)(\d+)', i))
        print(l)
elif 'or' in x:
    print(x)

this gives
cars>=20 
[[('>=', '20')]]
jeeps =='one'
[[('>=', '20')], []]

Excepted output:

['20','one']

Upvotes: 1

Views: 301

Answers (2)

Scott Hunter
Scott Hunter

Reputation: 49883

This doesn't use re, but (almost) produces the desired output (quotes are left around one):

x = "cars>=20 and jeeps =='one'"
if 'and' in x:
    r=x.split('and')
    l=[]
    for i in r:
        for op in ('>=','=='):
            r2 = i.split(op)
            if len(r2) > 1:
                l.append(r2[-1])
                break
    print(l)
elif 'or' in x:
    print(x)

Upvotes: 1

Jan
Jan

Reputation: 43169

You could use

(?P<key>\w+)\s*[<>=]+\s*'?(?P<value>\w+)'?

See a demo on regex101.com.


In Python this could be:

import re

rx = re.compile(r"""(?P<key>\w+)\s*[<>=]+\s*'?(?P<value>\w+)'?""")
x = "cars>=20 and jeeps =='one'"

result = {m.group('key'): m.group('value') for m in rx.finditer(x)}
print(result)

Which would yield

{'cars': '20', 'jeeps': 'one'}

See another demo on ideone.com.

Upvotes: 1

Related Questions