嘗試以下操作:
#!python3
import re
line = 'line=a name="12123" adfii 41:05:992 wp=wp2 this is the rate: controlled not max; time=300 loops for the system: process=16.0 sharesize=6b2k'
pattern = r'(\w+)=(\w+|".+?")'
lst = re.findall(pattern, line)
print(lst)
d = dict(lst)
print(d)
print(d['process'])
它打印出我的屏幕上顯示如下:
c:\tmp\___python\njau_ndirangu\so13758903>py a.py
[('line', 'a'), ('name', '"12123"'), ('wp', 'wp2'), ('time', '300'), ('process', '16'), ('sharesize', '6b2k')]
{'line': 'a', 'sharesize': '6b2k', 'time': '300', 'name': '"12123"', 'process': '16', 'wp': 'wp2'}
16
當然,你也可以直接寫:
d = dict(re.findall(r'(\w+)=(\w+|".+?")', line))
.findall
返回匹配列表,其中一個匹配表示爲具有子集的元組roups作爲元素(在模式內的括號裏的東西)。
但要小心正則表達式。你可以很容易犯一個錯誤。