2010-12-14 41 views
0
str = "a\b\c\dsdf\matchthis\erwe.txt" 

最後一個文件夾名稱。Python:正則表達式幫助

匹配 「matchthis」

+1

'matchthis' .... – 2010-12-14 06:50:04

+1

不需要正則表達式;只需使用'str.split(「\\」)'或類似的。 – chrisaycock 2010-12-14 06:50:44

+1

使用目錄更好地使用os.path而不是拆分 – Rozuur 2010-12-14 07:10:28

回答

2

最好使用os.path.split(path)因爲它是獨立的平臺。你必須調用它兩次才能得到最終目錄:

path_file = "a\b\c\dsdf\matchthis\erwe.txt" 
path, file = os.path.split(path_file) 
path, dir = os.path.split(path) 
0
x = "a\b\c\d\match\something.txt" 
match = x.split('\\')[-2] 
1
>>> str = "a\\b\\c\\dsdf\\matchthis\\erwe.txt" 
>>> str.split("\\")[-2] 
'matchthis' 
0
>>> import re 
>>> print re.match(r".*\\(.*)\\[^\\]*", r"a\b\c\dsdf\matchthis\erwe.txt").groups() 
('matchthis',) 

由於@chrisaycock和@雷夫 - 克託萊指出。如果可以,請使用x.split(r'\')。它速度更快,可讀性更強,更加pythonic。如果你真的需要一個正則表達式然後使用一個。編輯: 其實,os.path是最好的。平臺無關。 UNIX/Windows的等

3

沒有使用正則表達式,只是做:

>>> import os 
>>> my_str = "a/b/c/dsdf/matchthis/erwe.txt" 
>>> my_dir_path = os.path.dirname(my_str) 
>>> my_dir_path 
'a/b/c/dsdf/matchthis' 
>>> my_dir_name = os.path.basename(my_dir_path) 
>>> my_dir_name 
'matchthis' 
+0

+1,平臺獨立和顯式。 – kevpie 2010-12-14 07:27:24