2010-12-09 214 views
1

值我有一個這樣的字符串:Python的搜索字符串

STAT bytes 0 
STAT curr_items 0 
STAT total_items 0 
STAT evictions 0 
STAT reclaimed 0 
END 

我試圖讓curr_items的值,到目前爲止,我已經得到了

out = telnet.read_until("END") 
req = re.search("curr_items", out).group(0).split()[0] 

它返回curr_items ,我如何獲得價值?

感謝

+0

什麼價值喲期望得到什麼? – 2010-12-09 10:05:12

回答

6

您可以添加一個capture group值匹配您的正則表達式:

>>> int(re.search("curr_items (\d+)", out).group(1)) 
0 
+0

這是比khachik提交的更好的解決方案嗎? – Tom 2010-12-09 10:10:35

1

re.search("curr_items [0-9]*", out).group(0).split()[1]

1
try: 
    req = int(re.search("(?<=curr_items)\s*([\d]*)", out).group(0)) 
except: 
    # No value was found. 
    req = defaultValue