[英]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. 我正在尝试提取方括号之间的方程式,但我不知道如何在python 2.7中进行。
i tried re.findall
but i think the pattern is wrong. 我尝试过
re.findall
但我认为模式是错误的。
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
它不返回任何内容而不是
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]
. 要从列表中获取字符串(
re.findall()
返回一个list
),可以通过索引位置零访问它: re.findall(pattern, child)[0]
。 But also the other methods for re
could be interesting for you, ie re.search()
or re.match()
. 但是其他
re
方法可能对您来说很有趣,即re.search()
或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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.