Ad
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
Ad
Answer
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, i.e. 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'
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad