利用正则表达式实现计算器功能
1 # 关键是匹配模式‘\(([^()]+)\)’匹配括号内无括号的内容,分组和^很巧妙的实现了匹配括号以外的字符 2 import re 3 4 origin = '1 - 2 * ((60-30 + (-40.0/5) * (9-2*5/3+7/3*99/4*2998 +10*568/14)) - (-4*3)/(16-3*2))' 5 6 def jisuan(args): 7 value = eval(args) 8 return value 9 while True: 10 result= re.split('\(([^()]+)\)',origin,1) 11 if len(result)==3: 12 before = result[0] 13 content = result[1] 14 after = result[2]
#上面等价于before,content,after = result 15 r = jisuan(content) 16 new_str = before + str(r) + after 17 origin = new_str 18 else: 19 print(jisuan(origin)) 20 break