b)&(ab)&(a= 0: current.append(s) -6ren">
gpt4 book ai didi

python - 提取两个括号之间的字符串,包括python中的嵌套括号

转载 作者:行者123 更新时间:2023-12-02 20:06:40 24 4
gpt4 key购买 nike

如何提取两个括号之间的字符串,包括嵌套的括号。

有一个字符串:

""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()",...]

格式不固定,字符串可能包含多个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

最佳答案

>>> 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()']


要匹配任意数量的嵌套对,您可以使用 regex模块,参见 Recursive Regular Expressions

关于python - 提取两个括号之间的字符串,包括python中的嵌套括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54455775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com