2014-10-08 192 views
1

我有一個正則表達式,但它不適用於所有情況。Python - 正則表達式dir

我需要它能夠匹配的任何情況下,以下幾點:

如果這個詞「test_word」在聲明中返回true

我一直是用什麼還沒有工作

('^/[^/]*/test_word/.+') 

('^/test_word/.+')** 

所以我在陳述匹配與顯示目錄,如:

/user/test_word 
/test_word 
/test_word/test_word/ 
/something/something/test_word/ 

和任何你能想到的事情都可能發生。

+0

爲什麼不直接使用( 'test_word')? test_word是否必須是一個目錄名稱本身? (是/ test_word2 /一個匹配?) – Tommy 2014-10-08 16:16:55

+0

我必須對此進行編輯。不知道我是否應該發佈新帖子。 – user3590149 2014-10-08 16:59:23

+0

對不起,我錯過了一個關鍵要求...請參閱額外的發佈。 http://stackoverflow.com/questions/26262426/python-regex-for-dir-of-certain-depth – user3590149 2014-10-08 17:01:40

回答

0

在結束它只是這一點 -

/test_word/?$ 

在中間或結尾,它的這一點 -

/test_word(?:/|$) 

DEMO

0

保持簡單:你想要test_word作爲一個完整路徑名部分(未較大字的一部分),所以無論是用斜線或字符串的開始或結束所包圍:

(^|/)test_word($|/) 

然而,更好的解決辦法是,打破了路徑成組件,然後使用精確匹配:

pathname = "/usr/someone/test_word" 
return "test_word" in pathname.split("/") 

試試吧。

+0

這種情況下是否敏感?如何使非大小寫敏感? – user3590149 2014-10-08 18:38:47

+0

你想不區分大小寫?你從來沒有說過這些。使用正則表達式,將「(?i)」添加到正則表達式中。爲了進行精確比較,在分割和比較之前,將小寫字符串('test_word'和'pathname')與'lower()'進行比較。 – alexis 2014-10-08 22:47:25

1

如果你知道它是一個路徑,只是想檢查test_word是否在那裏,你可以使用re.search在路徑的任何地方找到「test_word」,或者只是在路徑中的「test_word」。

如果你想確保它只是test_word,而不是像test_words,test_word9等,那麼你可以做這樣的事情:

import re 

dirs = ["/user/test_word", "/test_wordsmith", "/user/test_word2", "do not match", "/usr/bin/python", "/test_word","/test_word/test_word/","/something/something/test_word/", "/test_word/files", "/test_word9/files"] 

for dir in dirs: 

    if re.search('/test_word(/|$)', dir): 
     print(dir, '-> yes') 
    else: 
     print(dir, '-> no') 

你匹配一個正斜槓之後test_word,接着是正斜線或字符串/行的結尾。

輸出:

/user/test_word -> yes 
/test_wordsmith -> no 
/user/test_word2 -> no 
do not match -> no 
/usr/bin/python -> no 
/test_word -> yes 
/test_word/test_word/ -> yes 
/something/something/test_word/ -> yes 
/test_word/files -> yes 
/test_word9/files -> no