### 運用正則表達式不使用內置方法實現計算器

`#__author__:"Jay guo"#__date__:2016/9/12import redef check(s):    if re.findall("[a-zA-Z]",s):        return "quit"    else:        return sdef format(s):    s = s.replace(" ","")    s = s.replace("++","+")    s = s.replace("+-","-")    s = s.replace("-+","-")    s = s.replace("--","+")    return sdef mul_exc(s):    while True:        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))        else:            break    return sdef add_sub(s):    while True:        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))        else:            break    s = s.replace("(","")    s = s.replace(")","")    return sdef main():    while True:        user = input("PLZ input>>>>:  ")        user = check(user)        if user == "quit":            print ("False")            continue        user = format(user)        user = "(" + user + ")"        while True:            ret = re.search("\([^()]*\)",user)            if ret:                ret = ret.group()                ret1 = mul_exc(ret)                ret1 = add_sub(ret1)                user = user.replace(ret,ret1)                user = format(user)            else:                user = add_sub(user)                break        print("結果",user)main()`

#### 注意！

© 2014-2021 ITdaan.com