Reputation: 51211
str = "a\b\c\dsdf\matchthis\erwe.txt"
The last folder name.
Match "matchthis"
Upvotes: 0
Views: 139
Reputation: 26088
>>> import re
>>> print re.match(r".*\\(.*)\\[^\\]*", r"a\b\c\dsdf\matchthis\erwe.txt").groups()
('matchthis',)
As @chrisaycock and @rafe-kettler pointed out. Use the x.split(r'\') if you can. It is way faster, readable and more pythonic. If you really need a regex then use one.
EDIT: Actually, os.path is best. Platform independent. unix/windows etc.
Upvotes: 0
Reputation: 4728
Better to use os.path.split(path)
since it's platform independent. You'll have to call it twice to get the final directory:
path_file = "a\b\c\dsdf\matchthis\erwe.txt"
path, file = os.path.split(path_file)
path, dir = os.path.split(path)
Upvotes: 2
Reputation: 5432
Without using regex, just do:
>>> 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'
Upvotes: 3
Reputation: 37930
>>> str = "a\\b\\c\\dsdf\\matchthis\\erwe.txt"
>>> str.split("\\")[-2]
'matchthis'
Upvotes: 1