Вот пример для нахождения и разделения текста между if
и then
Результатом является список отдельных элементов: переменных, скобок и операторов сравнения.
code = """
If MarketPosition = 0 and (EntriesToday(Date) < 1 or EndofSess) and
EntCondL
then begin
Buy("EnStop-L") NShares shares next bar at EntPrL stop;
end;
"""
import re
words = re.split("\s+|(\(|\)|<|>|=|;)", code)
is_if = False
results = []
current = None
for token in words:
if not token:
continue
elif token.lower() == "if":
is_if = True
current = []
elif token.lower() == "then":
is_if = False
results.append(current)
elif is_if:
if token.isdecimal(): # Detect numbers
try:
current.append(int(token))
except ValueError:
current.append(float(token))
else: # otherwise just take the string
current.append(token)
print(results)
Результат:
['MarketPosition', '=', 0, 'and', '(', 'EntriesToday', '(', 'Date', ')', '<', 1, 'or', 'EndofSess', ')', 'and', 'EntCondL']
Я думаю, что отсюда проще перейти (не знаю, в каком виде вам нужны данные, например, имеют ли значение скобки?)