Comment extraire la chaîne entre deux supports, y compris les supports imbriqués.
Il y a une chaîne: p> Comment puis-je extraire tout le contenu de Si () Code> Comme suit: P> 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
4 Réponses :
if((a>b)&(a<c),(a+b)*c,(a-b)*c)
Qu'en est-il de "" résultat = sqrt (si ((((a> b) & (a> b) & (a
Cela ressemblait à une manipulation de chaîne fixe, mais je vais éditer et ajouter une approche globale après le déjeuner, acclamations
Bon appétit :)
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)
NOTE:This is not a real parser. If you want to create a parser that matches LALR(1) grammar, maybe the PLY is what you are looking for. It can help you to build a complete parser.
Essayez ceci:
st[st.find('(')+1:st.rfind(')')]
>>> 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()']
Si toutes vos entrées sont sous la forme "VARNAME = FUNCNAME (expression)", il est tout à fait facile - il suffit de trouver la position de la première paren ouverte et vous êtes essentiellement fait. Maintenant, si vous voulez pouvoir analyser les expressions / déclarations arbitraires, vous aurez besoin d'un analyseur approprié pour cette langue, quoi que ce soit.
Tomassetti.me/Parsing-In-python
@brunodesthuilliers, oui, c'est ce que je veux faire exactement.
@Jimmy "Oui, c'est ce que je veux exactement faire" => quoi?