user469652
user469652

Reputation: 51211

Python: Regex help

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

The last folder name.

Match "matchthis"

Upvotes: 0

Views: 139

Answers (5)

kevpie
kevpie

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

Don O'Donnell
Don O'Donnell

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

Geoffrey
Geoffrey

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

chrisaycock
chrisaycock

Reputation: 37930

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

Upvotes: 1

Rafe Kettler
Rafe Kettler

Reputation: 76945

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

Upvotes: 0

Related Questions