Reputation: 1140
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
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.P.S - For such kind of this you should use standard libraries available instead of regex.
Upvotes: 3
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
Reputation: 619
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