简体   繁体   中英

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']

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM