如果你知道它是一個路徑,只是想檢查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
爲什麼不直接使用( 'test_word')? test_word是否必須是一個目錄名稱本身? (是/ test_word2 /一個匹配?) – Tommy 2014-10-08 16:16:55
我必須對此進行編輯。不知道我是否應該發佈新帖子。 – user3590149 2014-10-08 16:59:23
對不起,我錯過了一個關鍵要求...請參閱額外的發佈。 http://stackoverflow.com/questions/26262426/python-regex-for-dir-of-certain-depth – user3590149 2014-10-08 17:01:40