简体   繁体   English

用python中的正则表达式匹配数学表达式

[英]Match mathematical expression with regex in python

I am unfortunately pretty unfamiliar to regular expressions. 不幸的是,我不熟悉正则表达式。 At the moment I try to replace some mathematical functions of the form a**b with pow(a, b) . 目前,我尝试用pow(a, b)替换a**b形式a**b一些数学函数。 Here is an example: 这是一个例子:

import re 
s = "8*pi**3*sin(x3)*sin(pi*z)**2" 
r = "[^*]\w*[*][*]\d"

This approach leads to: 这种方法导致:

In [64]: re.findall(r, s)
Out[64]: ['pi**3', ')**2']

So in the second case the * inside the sin function is the end of the match, but it should be 'sin(pi*z)**2' . 因此,在第二种情况下,sin函数中的*是比赛的结尾,但应为'sin(pi*z)**2' I am not sure how to ignore the * inside the brackets. 我不确定如何忽略方括号内的* Thank you for any suggestions 谢谢你的任何建议

Instead of using regex this can be solved by using the sympy ccode function for example: 可以使用sympy ccode函数来解决此问题,而不是使用正则表达式:

from sympy.printing import ccode
from sympy.parsing.sympy_parser import parse_expr

s = "8*pi**3*sin(x3)*sin(pi*z)**2" 
exp = parse_expr(s)

In [55]: ccode(exp) 
Out[55]: '8*pow(M_PI, 3)*sin(x3)*pow(sin(M_PI*z), 2)'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM