[英]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.