1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))求上述表示式的結果
分析:對於上述表示式,涉及的括號及運算子較多,需使用正規表示式來匹配相應的字元,將字元進行分開計算
1、提取最裡層括號裡面的內容
2、計算最裡層括號內的乘除運算,並將結果替換到原表示式
3、迴圈執行前兩步的結果
1importre2
#formula = "1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))"3#
#含義:匹配括號,但是不匹配成對的括號,按正規表示式進行分割,最大分割次數為1次,取出最內層的括號內的一組元素4#
val = re.split('\(([^()]+)\)',formula,1)5#
before,center,last=val6#
print(val)7#
#將取出的內容進行運算8#
if "*" in center:9#
new_center=re.split("\*",center)10#
sub_res=float(new_center[0])*float(new_center[1])11#
print("單步計算結果為:",sub_res)12#
13#elif "/" in center:14#
new_center=re.split("/",center)15#
sub_res=float(new_center[0])/float(new_center[1])16#
print("單步計算結果為:",sub_res)17#
18#formula=before+str(sub_res)+last19#
print(formula)20#
val1 = re.split('\(([^()]+)\)',formula,1)21#
print(val1)22#
val2= re.split('(\d+\.?\d*[*/][\-]?\d+\.?\d*)',formula,1)23#
print("val2:",val2)24#
before1,center1,last1=val225#
26#if "*" in center1:27#
new_center=re.split("\*",center1)28#
print("111:",new_center)29#
sub_res=float(new_center[0])*float(new_center[1])30#
print("單步計算結果為:",sub_res)31#
32#elif "/" in center1:33#
new_center=re.split("/",center1)34#
sub_res=float(new_center[0])/float(new_center[1])35#
print("單步計算結果為:",sub_res)
3637
3839
4041
#計算,首先利用正規表示式,匹配最內層括號,並取出最內層括號內的元素,然後進行最內層括號內運算
42def
calc(formula):
43while
true:44#
取最裡層括號裡面的內容,進行運算
45 val =re.split('
\(([^()]+)\)
',formula,1)
46if len(val)==3:
47 before,center,last=val
48 new_center=mul_div(center)
49 formula=before+str(new_center)+last
50else:51
return
mul_div(formula)
5253
defmul_div(formula):
54while
true:55#
取優先順序高的,進行拆分計算
56 val1=re.split('
(\d+\.?\d*[*/][\-]?\d+\.?\d*)
',formula,1)
57if len(val1)==3:
58 bef,cent,la=val1
59if"*
"incent:
60 new_cent=re.split("\*"
,cent)
61 sub_res=float(new_cent[0])*float(new_cent[1])
62 formula=bef+str(sub_res)+la
63elif"/
"incent:
64 new_cent=re.split("/"
,cent)
65 sub_res=float(new_cent[0])*float(new_cent[1])
66 formula=bef+str(sub_res)+la
67else:68
return
final(formula)
6970
deffinal(formula):71#
由前面的分析結果可以看出,拆分時運算子被拆分,但計算結果有時含有運算子,故需進行替換
72 formula = formula.replace('
++','
+').replace('
+-','
-').replace('
-+','
-').replace('
--','+'
)73 num = re.findall('
[+\-]?\d+\.?\d*
',formula)
74 total =0
75for i in
num:
76 total +=float(i)
77return
total
7879
8081
if__name__ == '
__main__':
82 formula = "
1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))
"83 result=calc(formula)
84print(result)
乙個正規表示式的例子
需求 通過.net的正則 上面3個都得到 aa 並對語句稍微講解一下。謝謝。http w 這個是我寫的。不知道怎麼加上或者匹配www 還有?這個什麼意思查不到。解決 i 匹配模式,表示忽略大小寫,在.net中等價於在後面加regexoptions.ignorecase引數 http www 肯定逆序...
乙個新人理解正規表示式
知識點 1 表單驗證 針對於 非空驗證 去空格 非空驗證是什麼呢,就是說 當我輸入乙個賬號的時候不能輸入乙個空格就完事了,乙個空格或者多個空格絕對不是賬號,我們接收乙個賬號的時候首先要做的就是把他的前後空格給去掉,然後判斷一下他是不是空的,如果是空的那麼就提示他輸入有誤。對比驗證 跟乙個值對比 就是...
乙個奇怪的正規表示式
昨天,我在做網路爬蟲的時候,遇到了乙個 對文字框的輸入作了編碼處理 具體作了什麼樣的處理,前面幾句用了js的replace方法,替換了一些特殊符號,後面用了乙個正規表示式進行了特殊的編碼工作。我當時的文字 acm task force on k 12 education and technology...