2013-10-28 28 views
1

我在Python中編寫了一個正則表達式來獲取字符串中的數字。但是,當我運行match.group()時,它說對象list沒有屬性group。我究竟做錯了什麼?我的代碼被粘貼到終端中,以及終端的響應。謝謝。Python不允許我使用正則表達式來做match.group()嗎?

>>> #import regex library 
... import re 
>>> 
>>> #use a regex to just get the numbers -- not the rest of the string 
... matcht = re.findall(r'\d', dwtunl) 
>>> matchb = re.findall(r'\d', ambaas) 
>>> #macht = re.search(r'\d\d', dwtunl) 
... 
>>> #just a test to see about my regex 
... print matcht.group() 
Traceback (most recent call last): 
    File "<stdin>", line 2, in <module> 
AttributeError: 'list' object has no attribute 'group' 
>>> print matchb.group() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'list' object has no attribute 'group' 
>>> 
>>> #start defining the final variables 
... if dwtunl == "No Delay": 
...  dwtunnl = 10 
... else: 
...  dwtunnl = matcht.group() 
... 
Traceback (most recent call last): 
    File "<stdin>", line 5, in <module> 
AttributeError: 'list' object has no attribute 'group' 
>>> if ambaas == "No Delay": 
...  ammbaas = 10 
... else: 
...  ammbaas = matchb.group() 
... 
Traceback (most recent call last): 
    File "<stdin>", line 4, in <module> 
AttributeError: 'list' object has no attribute 'group' 
+0

閱讀文檔:http://docs.python.org/2.7/library/re.html#re.findall :) – sebastian

回答

4

re.findall()不返回匹配對象(或它們的列表),它總是返回字符串列表(或字符串的元組的列表中,如果存在多於一個捕獲組的情況下, )。並且列表沒有.group()方法。

>>> import re 
>>> regex = re.compile(r"(\w)(\W)") 
>>> regex.findall("A/1$5&") 
[('A', '/'), ('1', '$'), ('5', '&')] 

re.finditer()將返回其產生每一個匹配的匹配對象的迭代器。

>>> for match in regex.finditer("A/1$5&"): 
...  print match.group(1), match.group(2) 
... 
A/
1 $ 
5 & 
0

因爲re.findall(r'\d', ambaas)返回list。您可以遍歷列表,如:

for i in stored_list 

或只是stored_list[0]

0

re.findall()返回字符串列表,而不是match對象。你可能意思是re.finditer