使用正则表达式实现(加减乘除)计算器(python实现)

import re#source为计算表达式字符串 source='((100-15*(10.2/2)))*10+(9+8/2*4)'#判断字符串中无效字符函数 def check(s): flag=True if re.findall('[a-zA-Z]',s): print('Invalid') flag=False returnflag#将表达式字符串中的空格,++等字符进行修正 def format(s): s=s.replace(' ','') s=s.replace('++','+') return s#加法和减法函数 def cal_add_sub(s): while re.search('\d+\.?\d*[-+]\d+\.?\d*', s): print(s) ret = (re.search('\d+\.?\d*[-+]\d+\.?\d*', s)).group() x, y = re.split('[-+]', ret) x = float(x) y = float(y) if re.search('\+',ret): ret1 = x + y s = re.sub('\d+\.?\d*[-+]\d+\.?\d*', str(ret1), s, 1) elif re.search('\-',ret): ret1 = x - y s = re.sub('\d+\.?\d*[-+/]\d+\.?\d*', str(ret1), s, 1) else: z=re.search('\d+\.?\d*',s).group() return z #乘法和除法函数 defcal_mul_div(s): while re.search('\d+\.?\d*[*/]\d+\.?\d*',s): print(s) ret = (re.search('\d+\.?\d*[*/]\d+\.?\d*', s)).group() x,y=re.split('[*/]',ret) x=float(x) y=float(y) if re.search('\*',ret): ret1=x*y print(ret1) s = re.sub('\d+\.?\d*[*/]\d+\.?\d*', str(ret1), s, 1) elif re.search('/',ret): ret1=x/y print(ret1) s = re.sub('\d+\.?\d*[*/]\d+\.?\d*', str(ret1), s, 1) else: z=cal_add_sub(s) return z#计算过程if check(source): strs=format(source) while re.search('\(',strs): ret=re.search('\([^()]+\)',strs).group() ret=cal_mul_div(ret) strs=re.sub('\([^()]+\)',cal_mul_div(ret),strs,1) else: strs=cal_mul_div(strs) print(strs)

【使用正则表达式实现(加减乘除)计算器(python实现)】

    推荐阅读