Search code examples
pythonpython-re

Regular expression to match as less characters as possible


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?


Solution

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