首页 > 代码库 > 正则表达式-计算器

正则表达式-计算器

利用正则表达式计算下面值:

1 - 2 * ( (60 - 30 + (-40.0/5) * (9 - 2 * 5/3 + 7 / 3 * 10/4*2 +10 *5/14)) -(-4*3)/(16-3*2))

 

技术分享
import re

def wipe(s): #定义去除重复+-号函数
    res=s.replace("+-","-").replace("++","+").replace("--","+").replace("-+","-")
    return res

def add_num(s):#定义加减法运算函数
    # s.replace("+-", "-").replace("++", "+").replace("--", "+").replace("-+", "-")
    wipe(s)
    while True:
        res = re.split("([+-]?\d+\.?\d*[\+-][+-]?\d+\.?\d*)", s)
        if len(res) == 3 and "+" in res[1]:
            a, b = res[1].split("+")
            res_s = float(a)+float(b)
            res[1] = res_s
            re.sub("([+-]?\d+\.?\d*[\+-][+-]?\d+\.?\d*)", str(res), s)
        elif len(res) == 3 and "-" in res[1]:
            a, b = res[1].split("-")
            res_s = float(a)-float(b)
            res[1] = res_s
            re.sub("([+-]?\d+\.?\d*[\+-][+-]?\d+\.?\d*)", str(res), s)

def mul(s):#定义乘除法运算
    while True:
        wipe(s)
        res=re.split("([+-]?\d+\.?\d*[\*/][+-]?\d+\.?\d*)", s)
        if len(res)==3 and "*"in res[1]:
            a,b=res[1].split("*")
            res_s=float(a)*float(b)
            res[1]=res_s
            re.sub("([+-]?\d+\.?\d*[\*/][+-]?\d+\.?\d*)",str(res),s)
        elif len(res)==3 and "/"in res[1]:
            a,b=res[1].split("/")
            res_s=float(a)/float(b)
            res[1]=res_s
            re.sub("([+-]?\d+\.?\d*[\*/][+-]?\d+\.?\d*)",str(res),s)



def get(s):#定义取括号内运算式函数
    res=re.sub(" ","",s)
    res1=re.search("\([^()]+\)",res).group()
    res2=res1.strip("()")
    return res2
计算器功能

 

正则表达式-计算器