我正在使用 Python 开发一个正则表达式,它将数学表达式转换为 Sympy 语言pow(x,y)中的幂格式。例如,它接受2^3并返回pow(2,3).
我目前的模式是:
# pattern
pattern = re.compile(r'(.+?)\^(.*)')
为了找到嵌套表达式的数学运算,我使用 for 循环来计算 ^(hat) 的数量,然后使用 re.sub 生成幂格式:
# length of the for loop
num_hat = len(re.findall(r'\^', exp))
# for nested pow
for i in range(num_hat):
exp = re.sub(pattern, r'pow(\1,\2)', exp)
return exp
此方法不适用于嵌套的 ^ 表达式,例如a^b^c^dorsin(x^2)^3因为最后括号的位置不正确。
因为a^b^c^d它返回pow(pow(pow(a,b,c,d)))
因为sin(x^2)^3它返回pow(pow(sin(x,2),3))
有什么办法可以克服这个问题吗?我尝试了负面前瞻,但它仍然无法正常工作
繁华开满天机
守候你守候我
繁花如伊
相关分类