0
A
回答
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
相關問題
- 1. Python的正則表達式的幫助
- 2. 幫助Python正則表達式
- 3. 正則表達式幫助python與alphanumaric
- 4. 正則表達式幫助Python?
- 5. Python的正則表達式的幫助
- 6. Python中的正則表達式幫助
- 7. Python - 正則表達式幫助
- 8. Python的正則表達式幫助
- 9. 正則表達式幫助
- 10. 正則表達式幫助
- 11. 正則表達式幫助
- 12. 幫助正則表達式
- 13. 正則表達式幫助
- 14. 正則表達式幫助
- 15. 正則表達式幫助
- 16. 幫助正則表達式
- 17. 幫助,正則表達式
- 18. 正則表達式幫助
- 19. 正則表達式幫助##### ##
- 20. 幫助正則表達式?
- 21. 幫助正則表達式
- 22. 正則表達式幫助
- 23. 幫助,正則表達式
- 24. 幫助正則表達式
- 25. 正則表達式幫助
- 26. 正則表達式幫助
- 27. 正則表達式幫助
- 28. 幫助,正則表達式
- 29. 正則表達式幫助
- 30. 正則表達式幫助
'matchthis' .... – 2010-12-14 06:50:04
不需要正則表達式;只需使用'str.split(「\\」)'或類似的。 – chrisaycock 2010-12-14 06:50:44
使用目錄更好地使用os.path而不是拆分 – Rozuur 2010-12-14 07:10:28