Conditional newcommand depending on characters

charactersconditionalsmacrosrenewcommand

I have a basic command I created, aimed to simply bold and move a text to gain time :

\newcommand*\Cote[1]{\footnotesize\emph{\textbf{#1}}}

When I want this result, I still have to use this command \Cote{My text}. I would like to automatize this, because the text I want to replace has always the same structure, which is to know a capital D with numbers next to it : D3 or D89 or D1023.

So I want a new command, which applies only when a number follows my letter D. Like this :

\newcommand*\D[1]{\footnotesize\emph{\textbf{#1}}}

but only when a number follows. Otherwise lots of my words would be replace and it would be a mess.

I tried to use a \ifnum0 command inside \newcommand, but unsuccessfully. Same failure trying to ferret around in other topics, like Conditionally replacing sequences of characters Any ideas ?

I use LuaLatex. A big thanks in advance !

Best Answer

This tokencycle seems to do the job. As you can see, intervening macros and groups in the input stream have no ill effects on the result.

\documentclass{article}
\usepackage{tokcycle,xcolor}
\Characterdirective{\ifx D#1\Cotetest{D}\else\addcytoks{#1}\fi}
\newcommand\Cotetest[1]{\tcpeek\z
  \ifx0\z\Cotetrue\else
  \ifx1\z\Cotetrue\else
  \ifx2\z\Cotetrue\else
  \ifx3\z\Cotetrue\else
  \ifx4\z\Cotetrue\else
  \ifx5\z\Cotetrue\else
  \ifx6\z\Cotetrue\else
  \ifx7\z\Cotetrue\else
  \ifx8\z\Cotetrue\else
  \ifx9\z\Cotetrue\else\addcytoks{#1}\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi}
\newcommand\Cotetrue{%
  \tcpop\z
  \expandafter\Cote\expandafter{\z}%
  \Cotetest{}}
\def\Cote#1{\addcytoks{\bgroup\footnotesize\emph{\textbf{#1}}\egroup}}
\begin{document}
\tokencyclexpress
D7C2
D93
\textcolor{red}{D123abc}
Dcf
D 
D\today
\endtokencyclexpress
\end{document}

enter image description here

SUPPLEMENT

In response to an OP comment, desiring to retain the "D" in the altered font, in the event of subsequent digits, I might do it this way:

\documentclass{article}
\usepackage{tokcycle,xcolor}
\Characterdirective{\ifx D#1\Cotetest{D}\else\addcytoks{#1}\fi}
\newcommand\Cotetest[1]{\tcpeek\z
  \ifx0\z\Cotetrue{#1}\else
  \ifx1\z\Cotetrue{#1}\else
  \ifx2\z\Cotetrue{#1}\else
  \ifx3\z\Cotetrue{#1}\else
  \ifx4\z\Cotetrue{#1}\else
  \ifx5\z\Cotetrue{#1}\else
  \ifx6\z\Cotetrue{#1}\else
  \ifx7\z\Cotetrue{#1}\else
  \ifx8\z\Cotetrue{#1}\else
  \ifx9\z\Cotetrue{#1}\else\addcytoks{#1}\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi}
\newcommand\Cotetrue[1]{%
  \tcpop\z
  \expandafter\Cote\expandafter{\expandafter#1\z}%
  \Cotetest{\empty}}
\def\Cote#1{\addcytoks{\bgroup\footnotesize\emph{\textbf{#1}}\egroup}}
\begin{document}
\tokencyclexpress
D7C2
D93
\textcolor{red}{D123abc}
Dcf
D 
D\today
\endtokencyclexpress
\end{document}

enter image description here