Remove part of the path

I have the following data:

/​share/​Downloads/​Videos/​Movies/​Big.Buck.Bunny.​720p.​Bluray.​x264-BLA.​torrent/Big.Buck.Bunny.​720p.​Bluray.​x264-BLA

      

However, I don't want to have "Big.Buck.Bunny. 720p. Bluray. X264-BLA.torrent /" in it, I want the path to be like this:

/​share/​Downloads/​Videos/​Movies/Big.Buck.Bunny.​720p.​Bluray.​x264-BLA

      

With regexp, I basically want math that contains * .torrent. /, How can I accomplish this in regexp?

Thank!

+3


source to share


5 answers


Basically I want the math to contain * .torrent. /, How can I accomplish this in regexp?

You can use:



[^/]*\.torrent/

      

Assuming the latter .

was a typo.

+1


source


You don't even need regular expressions. You can use os.path.dirname

and os.path.basename

:

os.path.join(os.path.dirname(os.path.dirname(path)),
             os.path.basename(path))

      

where path

is the original path to the file.



Alternatively, you can also use os.path.split

like this:

dirname, filename = os.path.split(path)
os.path.join(os.path.dirname(dirname), filename)

      

Note. This will work on the assumption that what you want to delete is the directory name that contains the file from the path, as in the example in the question.

+11


source


You can do this without using regexp:

>>> x = unicode('/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA.torrent/Big.Buck.Bunny.720p.Bluray.x264-BLA')
>>> x.rfind('.torrent')
66
>>> x[:x.rfind('.torrent')]
u'/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA'

      

+4


source


Considering path='/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA.torrent/Big.Buck.Bunny.720p.Bluray.x264-BLA'

You can do it with regex like

re.sub("/[^/]*\.torrent/","",path)

      

You can also do it without regex as

'/'.join(x for x in path.split("/") if x.find("torrent") == -1)

      

+1


source


Your question is a bit vague and unclear, but here is one way to reverse what you want:

import re
s = "/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA.torrent/Big.Buck.Bunny.720p.Bluray.x264-BLA"

c = re.compile("(/.*/).*?torrent/(.*)")
m = re.match(c, s)
path = m.group(1)
file = m.group(2)
print path + file

>>> ## working on region in file /usr/tmp/python-215357Ay...
/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA

      

0


source







All Articles