Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python windows path regex

Tags:

python

regex

I've spent the last two hours figuring this out. I have this string:

C:\\Users\\Bob\\.luxshop\\jeans\\diesel-qd\\images\\Livier_11.png 

I am interested in getting \\Livier_11.png but it seems impossible for me. How can I do this?

like image 325
XRaycat Avatar asked Nov 17 '25 16:11

XRaycat


1 Answers

I'd strongly recommend using the python pathlib module. It's part of the standard library and designed to handle file paths. Some examples:

>>> from pathlib import Path
>>> p = Path(r"C:\Users\Bob\.luxshop\jeans\diesel-qd\images\Livier_11.png")
>>> p
WindowsPath('C:/Users/Bob/.luxshop/jeans/diesel-qd/images/Livier_11.png')
>>> p.name
'Livier_11.png'
>>> p.parts
('C:\\', 'Users', 'Bob', '.luxshop', 'jeans', 'diesel-qd', 'images', 'Livier_11.png')
>>> # construct a path from parts
...
>>> Path("C:\some_folder", "subfolder", "file.txt")
WindowsPath('C:/some_folder/subfolder/file.txt')
>>> p.exists()
False
>>> p.is_file()
False
>>>

Edit:

If you want to use regex, this should work:

>>> s = "C:\\Users\\Bob\\.luxshop\\jeans\\diesel-qd\\images\\Livier_11.png"
>>> import re
>>> match = re.match(r".*(\\.*)$", s)
>>> match.group(1)
'\\Livier_11.png'
>>>
like image 104
Felix Avatar answered Nov 19 '25 06:11

Felix