XRaycat
XRaycat

Reputation: 1140

Python windows path 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?

Upvotes: 3

Views: 11320

Answers (3)

Code Maniac
Code Maniac

Reputation: 37755

You can use this

^.*(\\\\.*)$

Explanation

  • ^ - Anchor to start of string.
  • .* - Matches anything except new line zero or time (Greedy method).
  • (\\\\.*) - Capturing group. Matches \\ followed any thing except newline zero or more time.
  • $ - Anchor to end of string.

Demo

P.S - For such kind of this you should use standard libraries available instead of regex.

Upvotes: 3

Felix
Felix

Reputation: 6359

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'
>>>

Upvotes: 6

If you can clearly say that "\\" is a delimiter (does not appear in any string except to separate the strings) then you can say:

str = "C:\\Users\\Bob\\.luxshop\\jeans\\diesel-qd\\images\\Livier_11.png"
spl = str.split(“\\”) #split the string
your_wanted_string = spl[-1]

Please note this is a very simple way to do it and not always the best way! If you need to do this often or if something important depends on it use a library! If you are just learning to code then this is easier to understand.

Upvotes: 2

Related Questions