2017-07-27 47 views
0

我想檢查前面沒有[a-zA-Z]之前的字符串attachmentPython3再次向前看負向不起作用

def is_attachment_url(url): 
    """check url""" 
    pattern = '(?<![\w]+)attachment' 
    return re.search(pattern, url, re.I) 


tests = (
    'article_?attachment', # should be false 
    'article_fattachment', # should be false 
    'article_-attachment', # should be true 
    'article_/attachment', # should be true 
) 
for ss in tests: 
    print(is_attachment_url(ss)) 

錯誤提示:

raise error("look-behind requires fixed-width pattern") 
sre_constants.error: look-behind requires fixed-width pattern 
+0

爲什麼會'article_ attachment'是假的,但'article_-attachment'?是真實的?在這兩個示例中,「附件」一詞前面都有一個非單詞字符 – Addison

+1

[Python正則表達式引擎 - 「後退需要固定寬度模式」錯誤]的可能重複(https://stackoverflow.com/questions/20089922/ – Addison

+0

當在'?'後面加上'attachment'時,它可能不是附件,當'-'後面的'attachment'可能是'''附件url',所以我'附件'不應該在'[az]'或'-'或'/'之後 – Mario7

回答

0

在圖案的+使得可變寬度。你不需要它,因爲你只需要檢查「附件」前的一個字符,所以只是將其刪除:

pattern = '(?<![\w])attachment'