让我们假设在前缀形式中有这个产品总和boolean expresion:
Or
And
和import ast
import re
or_op = ' OR '
and_op = ' AND '
str_formula = str_formula.replace('Or(', '[').replace('And(', '[').replace(')', ']')
s_list = re.sub('(\w+)', r"'\1'", str_formula)
list_formula = [x if isinstance(x, list) else [x] for x in ast.literal_eval(s_list)]
infix_form = or_op.join([and_op.join(sublist) for sublist in list_formula])
是唯一允许的运算符,并且没有比上面表示的嵌套结构更多的嵌套结构。我想重写表达式以便接收中缀表单。
我的想法,不使用正则表达式,是:
'A OR B AND C AND D OR E OR F OR G AND H'
infix_form变量是:
eval
你能建议一个正则表达式,以更聪明的方式解决这个问题吗?
答案 0 :(得分:1)
使用re.sub()
函数和替换回调replaceOperands
,考虑以下方法:
str_formula = 'Or(A, And(B, C, D), E, F, And(G, H))'
def replaceOperands(m):
s = re.sub(r'\(|\)', '', m.group(2).replace(',', ' OR')) if m.group(1) == 'Or' else '('+m.group(2).replace(',', ' AND')+')'
return s
str_formula = re.sub(r'\b(Or)\(([A-Z], (?:\(.*\))[A-Z]?)',
replaceOperands,
re.sub(r'\b(And)\(([^)]+)\)', replaceOperands, str_formula))
print(str_formula)
输出:
A OR B AND C AND D OR E OR F OR G AND H