簡體   English   中英

如何提取括號python 2.7之間的方程式?

[英]How to extract equation between brackets Python 2.7?

我正在嘗試提取方括號之間的方程式,但我不知道如何在python 2.7中進行。

我嘗試過re.findall但我認為模式是錯誤的。

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

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

它不返回任何內容而不是x1<25)*2 +((x1>=25)&&(x2<200))*2+((x1>=25)&&(x2>=200))*1

似乎您只對{}之間的所有內容感興趣,因此您的正則表達式可能更簡單:

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)

輸出是這樣的:

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

要從列表中獲取字符串( re.findall()返回一個list ),可以通過索引位置零訪問它: re.findall(pattern, child)[0] 但是其他re方法可能對您來說很有趣,即re.search()re.match()

但是,如果每個字符串在第一個和最后一個位置都有前導括號和結尾括號,您也可以簡單地執行以下操作:

child[1:-1]

這給你

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

您可以使用此正則表達式- {([^}]*)} 它匹配的字符{然后[^}]*匹配任何東西,除了}}端托架相匹配。

>>> 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM