2014-10-08 193 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