# Regular expression with listings to extract filename from path

When using \lstinputlisting{./../src/main.py} I'm using relative paths to access the Python source file.

However, I would like to automatically exclude the relative path part leaving just the filename, so that the title/caption appears like this main.py and not like ./../src/main.py

I would assume some regular expression could solve my problem, but how ?

Simplified LaTeX code:

\documentclass[11pt]{article}
\usepackage{listings}

\lstset {
title = \lstname % <- regular expression to extract filename
}

\begin{document}
\lstinputlisting{./../src/main.py}
\end{document}

• there is a option inputpath=./../src/ that you can feed into \lstset. With that, TeX should be able to find the path-less input file in that folder. – Lupino Oct 29 '19 at 12:20

You can specify the path with the inputpath option to \lstset and provide the file name with an intermediary macro:

\documentclass[11pt]{article}
\usepackage{listings}

\lstset {
inputpath=./../src,
title = \myname
}

\begin{document}
\def\myname{main.py}
\lstinputlisting{\myname}

\def\myname{test.py}
\lstinputlisting{\myname}
\end{document}


EDIT: a more generic and easier to handle approach would be to strip away the path part as long as your source files are always located in a folder named src:

\documentclass[11pt]{article}
\usepackage{listings}

\def\extractPath#1src/#2\relax{#2}
\lstset{title = \expandafter\extractPath\lstname\relax}

\begin{document}
\lstinputlisting{./../src/main.py}
\lstinputlisting{./../src/test.py}
\end{document}


expl3 got you covered. There is a function built in \file_parse_full_name:nNNN, which we can use here. I created a macro from it which you can use to typeset different parts of the file name. If the optional argument includes a d the directory will be printed, if it contains an f the file name will be printed, if it contains an e the extension will be printed, order doesn't matter. By default it uses fe so prints the file name and the extension, but not the directory (as you wanted it to be).

\documentclass[11pt]{article}
\usepackage{listings}

\usepackage{xparse}

\ExplSyntaxOn
\tl_new:N \l_Skjerning_dir_tl
\tl_new:N \l_Skjerning_file_tl
\tl_new:N \l_Skjerning_ext_tl
\NewDocumentCommand \GetFileName { O{fe} m }
{
\file_parse_full_name:eNNN { #2 }
\l_Skjerning_dir_tl
\l_Skjerning_file_tl
\l_Skjerning_ext_tl
\tl_if_in:nnT { #1 } { d } { \l_Skjerning_dir_tl / }
\tl_if_in:nnT { #1 } { f } \l_Skjerning_file_tl
\tl_if_in:nnT { #1 } { e } \l_Skjerning_ext_tl
}
\cs_generate_variant:Nn \file_parse_full_name:nNNN { eNNN }
\ExplSyntaxOff

\lstset {
title = {\GetFileName{\lstname}}
}

\begin{document}
\lstinputlisting{./../src/main.py}
\end{document}


• Thank you! However, I think I will go with @Lupino answer as it is more simply and works for this particular case. But I'll save your answer for a larger project that I have in mind. – Christian Skjerning Oct 29 '19 at 13:59