0
str = "a\b\c\dsdf\matchthis\erwe.txt"

The last folder name.

Match "matchthis"

2
  • 1
    No need for regex; just use str.split("\\") or similar. Commented Dec 14, 2010 at 6:50
  • 1
    working with directories its better to use os.path instead of splitting Commented Dec 14, 2010 at 7:10

5 Answers 5

3

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'
Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

1
>>> str = "a\\b\\c\\dsdf\\matchthis\\erwe.txt"
>>> str.split("\\")[-2]
'matchthis'

Comments

0
x = "a\b\c\d\match\something.txt"
match = x.split('\\')[-2]

Comments

0
>>> 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.