首页 > 代码库 > 运用正则表达式不使用内置方法实现计算器

运用正则表达式不使用内置方法实现计算器

#__author__:"Jay guo"#__date__:2016/9/12import redef check(s):    if re.findall("[a-zA-Z]",s) or re.findall("[*/][^\d(]",s):        return    else:        return sdef format(s):    s = s.replace(" ","")    s = s.replace("++","+")    s = s.replace("+-","-")    s = s.replace("-+","-")    s = s.replace("--","+")    return sdef add_sub(s):    ret = re.search("\d+\.?\d*[+-]\d+\.?\d*", s)    if ret:        x, y = re.split("[+-]", ret.group())        x = float(x)        y = float(y)        if "+" in ret.group():            end = x + y        else:            end = x - y        s = s.replace(ret.group(), str(end))        s = s.replace("(","")        s = s.replace(")","")    return sdef mul_exc(s):    ret = re.search("\d+\.?\d*[*/]\d+\.?\d*", s)    if  ret:        x,y = re.split("[*/]",ret.group())        x = float(x)        y = float(y)        if "*" in ret.group():            end = x*y        else:            end = x/y        s = s.replace(ret.group(),str(end))        s = s.replace("(","")        s = s.replace(")","")    return sdef main():    while True:        ret = input("PLZ input>>>>:  ")        ret = check(ret)        ret = format(ret)        while True:            ret = mul_exc(ret)            ret = add_sub(ret)            ret = format(ret)            a = len(re.findall("\d+", ret))            print ("a",a,ret)            if a == 2:                break        print (re.sub("^\+","",ret))main()

 

运用正则表达式不使用内置方法实现计算器