2009-03-05 80 views
2

我試圖在Python下面的正則表達式,但它返回一個錯誤爲什麼正則表達式在python中返回錯誤?

import re 
... 

#read a line from a file to variable line 
# loking for the pattern 'WORD' in the line ... 

m=re.search('(?<=[WORD])\w+',str(line)) 
m.group(0) 

我得到以下錯誤:

AttributeError的: 'NoneType' 對象有沒有屬性 '組'

回答

4

發生這種情況的原因是正則表達式不匹配。所以m是None,當然你不能訪問group [0]。在嘗試訪問組成員之前,您需要首先測試搜索是否成功。

+0

它實際上是m,即None。 (小尼特) – 2009-03-05 10:34:01

2

re.search documentation says

Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

2
>>> help(re.search) 
Help on function search in module re: 

search(pattern, string, flags=0) 
    Scan through string looking for a match to the pattern, returning 
    a match object, or None if no match was found. 

看看最後一行:如果沒有找到匹配

1

順便說一句,你的正則表達式是不正確返回無。 如果你尋找'WORD',它應該只是'WORD'。 str也是無關緊要的。您的代碼應該是這樣的:

m = re.search('WORD', line) 
if m: 
    print m.group[0] 

你原來的正則表達式將返回可能意外和意外的結果:

>>> m = re.search('(?<=[WORD])\w+', 'WORDnet') 
>>> m.group(0) 
'ORDnet' 
3

兩個問題:

  1. 你的模式不匹配,因此m設置爲None,並且None沒有group屬性。

  2. 我相信你的意思之一:在

    m= re.search(r"(?<=WORD)\w+", str(line)) 
    

    的進入,或

    m= re.search(r"(?P<WORD>\w+)", str(line)) 
    

    前者匹配 「ABC」 「WORDabc高清」;後者與「abc def」中的「abc」匹配,並且匹配對象將具有包含「abc」的.group("WORD")。 (在指定正則表達式時,使用r「」字符串通常是一個好主意。)

相關問題