本文實例講述了python正則表達式實現(xiàn)簡易計算器功能。分享給大家供大家參考,具體如下:
需求:使用正則表達式完成一個簡易計算器。
功能:能夠計算簡單的表達式。
如:1*2*((1+2)/(2+3)+1)*5.1-3+2**2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
import re class simplecalc( object ): # 表達式檢測 def check( self ,exp): # 合法字符檢測 res = re.findall(r "[^\d\+\-\*/\(\)\.]" , exp) print (res) if res: print ( "表達式不正確?。?!" ) print ( "輸入了非法字符:" , res) return false # 括號檢測 res = re.findall(r "(?:[\d\)]\()|(?:\([\*/\)])|(?:[\-\+\*/]\))" ,exp) if res : print ( "表達式不正確!?。?quot; ) print ( "括號使用有誤:" , res) return false res = re.findall(r "\(|\)" , exp) if res.count( '(' ) ! = res.count( ')' ): print ( "表達式不正確!?。?quot; ) print ( "括號不匹配:" , res) return false # 運算符檢測 res = re.findall(r "[\-\+/]{2,}|\*{3,}" , exp) if res: print ( "表達式不正確!!!" ) print ( "運算符有誤:" , res) return false # 小數(shù)點位置檢測 res = re.findall(r "(^(?<=[0-9])?\.\d+)|(\.\d*?\.)|\.(\d|$)" , exp) if res: print ( "表達式不正確!!!" ) print ( "小數(shù)點位置有誤:" , res) return false return true def main(): simplecalc = simplecalc() while true: exp = input ( "請輸入一個正確的表達式(退出請輸入t):\n" ) if exp = = 't' : break if simplecalc.check(exp): print ( '=' , eval (exp)) else : continue if __name__ = = '__main__' : main() |
輸出:
請輸入一個正確的表達式(退出請輸入t):
1*2*((1+2)/(2+3)+1)*5.1-3+2**2
[]
= 17.32
請輸入一個正確的表達式(退出請輸入t):
12+a
['a']
表達式不正確?。?!
輸入了非法字符: ['a']
請輸入一個正確的表達式(退出請輸入t):
ps:這里再為大家提供2款非常方便的正則表達式工具供大家參考使用:
正則表達式在線測試工具:https://tool.zzvips.com/t/regex/
正則表達式在線生成工具:https://tool.zzvips.com/t/regcode/
希望本文所述對大家python程序設(shè)計有所幫助。
原文鏈接:https://blog.csdn.net/lm_is_dc/article/details/80077405