2012-07-25 30 views
3

可能重複:
Python regular expressions - how to capture multiple groups from a wildcard expression?蟒正則表達式重複組匹配


我不能訪問該組爲第三或第五元件在以下的正則表達式:

>>> x = 'f 167 2958 335 3103 0' 
>>> re.search('.(\s\d+){5}', x).group() 
'f 167 2958 335 3103 0' 
>>> re.search('.(\s\d+){5}', x).group(1) 
' 0' 
>>> # how do i access no 2958 and 3103 

我知道我可以用pattern =來實現上面的'。\ s \ d + \ s(\ d +)\ s \ d + \ s(\ d +)\ s \ d +',但那是跛腳。

感謝, 阿米特

回答

3

您可以使用re.findall這一點。

result = re.findall('\s\d+', x) 

print result[1] # 2958 
print result[3] # 3103 
0

如果這是一個普遍問題,那麼findall是你最好的選擇。

如果這是你正在試圖做的事情實際,split會更有意義:

>>> x = 'f 167 2958 335 3103 0' 
>>> l = x.split() 
>>> l[2] 
'2958' 
>>> l[4] 
'3103'