retrieving substring of \DTLfetch

I've been trying to get to the substring of a value retrieved by datatool's, macro \DTLfetch, but I am unable to control the expansion here. I've tried some \expandarg \fullexpandarg as well as some \edef.

I don't necessarily need to use datatool to retrieve the contents or xstring to perform the substring-command,, but I am required to not alter the datafile. Otherwise, I would just have regex-ed it.

Code

\documentclass{article}

\usepackage{datatool}
\usepackage{xstring}

\usepackage{filecontents}

\begin{filecontents*}{data.csv}
x,y
duck,quack
donkey,hee-haw
\end{filecontents*}

\begin{document}

original value:
\DTLfetch{data}{x}{donkey}{y}%

substring(failing):
% \fullexpandarg%
\expandarg%
\StrRight{%
\DTLfetch{data}{x}{donkey}{y}%
}{3}

Expecting output:
\StrRight{%
hee-haw%
}{3}

\end{document}

• @egreg Is there a different package, or some kind of macro that can do this? Oct 23 '16 at 10:54

Unfortunately, \DTLfetch is not expandable, but there's a way out: \DTLfetch saves the returned value in \dtlcurrentvalue, so it's just a matter of making this available for processing in \StrRight and print nothing.

I just copied the definition of \DTLfetch, shifting the parameters by one and inserted \let#1 before \dtlcurrentvalue (that is causing the printing). Do \DTLfetchsave{\temp}{<1>}{<2>}{<3>}{<4>}, where the last four arguments mean the same as the arguments to \DTLfetch and \temp is any (unused) control sequence. You can reuse \temp or whatever name you chose; be careful to use a “strange name”.

\begin{filecontents*}{\jobname.csv}
x,y
duck,quack
donkey,hee-haw
\end{filecontents*}

\documentclass{article}

\usepackage{datatool}
\usepackage{xstring}

\newcommand{\DTLfetchsave}[5]{%
\edtlgetrowforvalue{#2}{\dtlcolumnindex{#2}{#3}}{#4}%
\dtlgetentryfromcurrentrow{\dtlcurrentvalue}{\dtlcolumnindex{#2}{#5}}%
\let#1\dtlcurrentvalue
}

\begin{document}

original value:
\DTLfetch{data}{x}{donkey}{y}%

substring:
\DTLfetchsave{\temp}{data}{x}{donkey}{y}%
\StrRight{\temp}{3}

Expecting output:
\StrRight{hee-haw}{3}

\end{document}