2013-07-09 86 views
1

我試圖將字符串拆分爲子字符串,按「AND」術語拆分,然後在 之後清理每個子字符串「garbage」。使用REGEX通過拆分字符串

下面的代碼得到的錯誤:

AttributeError: 'NoneType' object has no attribute 'group'

import re 
def fun(self, str): 
    for subStr in str.split('AND'): 
     p = re.compile('[^"()]+') 
     m = p.match(subStr) 
     print (m.group()) 
+0

'str'的​​值是什麼? – Racso

+2

這就是沒有匹配時會發生的情況......在嘗試對它們進行「分組」之前,您必須檢查「m」是否包含任何元素。 – Floris

+0

使用try和except? –

回答

1

這意味着match沒有找到,它返回None

請注意,您可能想在此處使用re.search而不是re.matchre.match僅匹配字符串的開頭,而re.search可以搜索字符串中的任何位置。

docs

Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default).

如果你已經知道,那麼你就可以搞定None使用:

if m: 
    print (m.group()) 
else: 
    #do something else 
1

如果上面的代碼是你真正想做的事,也不會首先使用string.translate去除垃圾比較容易。例如:

import string 

def clean_and_split(x): 
    return string.translate(x, None, r'^"()').split("AND")