1. 匹配一行字符串中 2个小数
匹配一行日志中先出现的2个小数,并取平均值
line ="AAAAAAAAAAAAAAAAAAAAAAAAA,curAsk0 5.5578516124999995, curBid0 5.608098387499999" p = r'.*curAsk0 ([\d].[\d]*)+.*curBid0 ([\d].[\d]*)' s = re.findall(p, line) s = list(s[0]) print(list(s)) for sell in s: sum = sum + float(sell) print(sum/2)
如上日志:一次匹配2个,则匹配到的值保存到s ,值为:[('5.5578516124999995','5.608098387499999')]
如上代码也可以修改为:
line = "AAAAAAAAAAAAAAAAAAAAAAAAA,curAsk0 5.5578516124999995, curBid0 5.608098387499999" p = r'.*curAsk0 ([\d.]+)+.*curBid0 ([\d.]+)' #修改了此处正则获取方式 s = re.findall(p, line) average = (float(s[0][0]) + float(s[0][0]))/2 print(average)