运用正则表达式不使用内置方法实现计算器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了运用正则表达式不使用内置方法实现计算器相关的知识,希望对你有一定的参考价值。
#__author__:"Jay guo" #__date__:2016/9/12 import re def check(s): if re.findall("[a-zA-Z]",s) or re.findall("[*/][^\d(]",s): return else: return s def format(s): s = s.replace(" ","") s = s.replace("++","+") s = s.replace("+-","-") s = s.replace("-+","-") s = s.replace("--","+") return s def 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 s def 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 s def 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()
以上是关于运用正则表达式不使用内置方法实现计算器的主要内容,如果未能解决你的问题,请参考以下文章