[英]Extract string between two brackets, including nested brackets in python
如何在兩個括號(包括嵌套的括號)之間提取字符串。
有一個字符串:
""res = sqr(if((a>b)&(a<c),(a+b)*c,(a-b)*c)+if()+if()...)""
我如何提取if()
的所有內容,如下所示:
["if((a>b)&(a<c),(a+b)*c,(a-b)*c)","if()","if()",...]
格式不是固定的,字符串可以包含multi- if
。 所以我想知道是否有可以匹配子字符串的模式。 稍后我將嘗試給出解決方案。 謝謝。
我的解決方案,如果有更好的方法,請向我指出:
def extractIfFunc(condStr):
startIndex = [m.start() for m in re.finditer('if\(',condStr)]
parts = []
for index in startIndex:
current = []
bracket_level = 0
for s in condStr[index+3:]:
if s != '(' and s != ')' and bracket_level >= 0:
current.append(s)
elif s == '(':
current.append(s)
bracket_level += 1
elif s == ')':
bracket_level -= 1
if bracket_level < 0:
current.append(s)
break
else:
current.append(s)
parts.append('if('+''.join(current))
return parts
嘗試這個:
st[st.find('(')+1:st.rfind(')')]
>>> import re
>>> s = """res = sqr(if((a>b)&(a<c),(a+b)*c,(a-b)*c)+if()+if()...)"""
>>> re.findall(r'if\((?:[^()]*|\([^()]*\))*\)', s)
['if((a>b)&(a<c),(a+b)*c,(a-b)*c)', 'if()', 'if()']
對於這種模式,最好使用VERBOSE
標志:
>>> lvl2 = re.compile('''
... if\( #literal if(
... (?: #start of non-capturing group
... [^()]* #non-parentheses characters
... | #OR
... \([^()]*\) #non-nested pair of parentheses
... )* #end of non-capturing group, 0 or more times
... \) #literal )
... ''', flags=re.X)
>>> re.findall(lvl2, s)
['if((a>b)&(a<c),(a+b)*c,(a-b)*c)', 'if()', 'if()']
st = """res = sqr(if((a>b)&(a<c),(a+b)*c,(a-b)*c))"""
print(st[10:][:-1])
輸出:
if((a>b)&(a<c),(a+b)*c,(a-b)*c)
編輯:
對於通用方法:
import re
st = """res = sqr(if((a>b)&(a<c),(a+b)*c,(a-b)*c))"""
pattern = "\((.*)\)"
print(re.compile(pattern).search(st).group(1))
哪里:
\\(
匹配字符(
按字面值(區分大小寫)
第一捕獲組(.*)
.*
匹配任何字符(行終止符除外)
\\)
)
從字面上匹配字符)
輸出:
if((a>b)&(a<c),(a+b)*c,(a-b)*c)
def extractIfFunc(condStr):
for i, segment in enumerate(a.split("if")):
if i == 0:
continue
s, n = -1, 0
for i, c in enumerate(segment):
if c == '(':
s = i if s < 0 else s
n += 1
elif c == ')':
n = n - 1 if n > 0 else 0
if n == 0 and s > -1:
yield "if(%s)" % segment[s + 1:i]
break
a = """res = sqr(if((a>b)&(a<c),(a+b)*c,(a-b)*c)+if()+if()...)"""
for segment in extractIfFunc(a):
print(segment)
注意:
這不是真正的解析器。 如果要創建與LALR(1)語法匹配的解析器,則可能是您要查找的PLY 。 它可以幫助您構建完整的解析器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.