如果你知道它是一个路径,只是想检查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