I want to match x.py from a/b/c/x.py, when I use re:
s = 'a/b/c/x.py'
res = re.search('/(.*.py)?', s).group(1)
>>> res = b/c/x.py
This is not what I need. Any ideas?
I want to match x.py from a/b/c/x.py, when I use re:
s = 'a/b/c/x.py'
res = re.search('/(.*.py)?', s).group(1)
>>> res = b/c/x.py
This is not what I need. Any ideas?
You don't need regex, just use str.rsplit, with maxsplit=1, and take the last item:
>>> s.rsplit('/',1)[-1]
'x.py'
when you want to extract filename from path, you should use os.path.split. The os.path.split() method in Python is used to Split the path name into a pair head and tail independent of OS. Here, tail is the last path name component and head is everything leading up to that.
import os
path = 'a/b/c/x.py'
res = os.path.split(path)
print(res[1])
You can also use normpath and os.sep for this solution:
import os
path = 'a/b/c/x.py'
path = os.path.normpath(path)
res = path.split(os.sep)
print(res[-1])
You can use rsplit as @ThePyGuy said in this case to avoid more splitting by changing the line to:
res = path.rsplit(os.sep,1)
import re
s = 'a/b/c/x.py'
res = re.search('\w*\.py', s).group() # It will match alphanumeric
# res = re.search(r'[\w&.-]+$', s).group()
# The above regex will match alphanumeric and the given special characters
EDIT
To match everything after the last / you can use following regex
res = re.search('[^/]+$', s).group()
I prefer a splitting approach here:
s = 'a/b/c/x.py'
last = s.split('/')[-1]
print(last) # x.py
If you need to ensure that the element is is the last in a path, you can prepend (?<=\/), a positive lookbehind:
>>> s = 'a/b/c/x.py'
>>> el = re.search(r"(?<=\/)(\w+\.py)", s).group(1)
>>> el
'x.py'
Otherwise, if you need to match also filename.py, you need to remove it:
>>> s2 = 'file.py'
>>> el = re.search(r"(\w+\.py)", s2).group(1)
>>> el
'file.py'