简体   繁体   中英

How to extract equation between brackets Python 2.7?

I'm trying to extract an equation between brackets but i don't know how to do it in python 2.7.

i tried re.findall but i think the pattern is wrong.

child = {(x1<25)*2 +((x1>=25)&&(x2<200))*2+((x1>=25)&&(x2>=200))*1}

stringExtract = re.findall(r'\{(?:[^()]*|\([^()]*\))*\}', child)

it returns nothing instead of x1<25)*2 +((x1>=25)&&(x2<200))*2+((x1>=25)&&(x2>=200))*1

It seems that you're only interested in everything between { and } , so your regex could be much simpler:

import re
child = "{(x1<25)*2 +((x1>=25)&&(x2<200))*2+((x1>=25)&&(x2>=200))*1}"    
pattern = re.compile("""
    \s*     # every whitespace before leading bracket
    {(.*)}  # everything between '{' and '}'
    \s*     # every whitespace after ending bracket
""", re.VERBOSE)
re.findall(pattern, child)

And the output is this:

['(x1<25)*2 +((x1>=25)&&(x2<200))*2+((x1>=25)&&(x2>=200))*1']

To get the string from the list ( re.findall() returns a list ), you can access it via index position zero: re.findall(pattern, child)[0] . But also the other methods for re could be interesting for you, ie re.search() or re.match() .

But if every string has a leading bracket and an ending bracket at first and last position, you can also simply do this:

child[1:-1]

which gives you

'(x1<25)*2 +((x1>=25)&&(x2<200))*2+((x1>=25)&&(x2>=200))*1'

You can use this regex - {([^}]*)} . It matches the character { then [^}]* matches anything except } and } matches the end bracket.

>>> import re
>>> eq = "{(x1<25)*2 +((x1>=25)&&(x2<200))*2+((x1>=25)&&(x2>=200))*1}"
>>> m = re.search("{([^}]*)}", eq)
>>> m.group(1)
'(x1<25)*2 +((x1>=25)&&(x2<200))*2+((x1>=25)&&(x2>=200))*1'

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