如果参数包含许多以 {} 分隔的标记,则吞噬该参数

如果参数包含许多以 {} 分隔的标记,则吞噬该参数

如何实现\mymacro具有一个参数和以下行为的宏:我想传递以下形式的参数\mymacro{some text}或两个嵌套参数,如\mymacro{{Text 1}{Text2}}。所需的输出如下:

\mymacro{Some text}        ->   Some text 
\mymacro{{Some text}}      ->   Some text 
\mymacro{{Text 1}{Text 2}} ->   1: Text 1 / 2: Text 2

那么,我如何测试是否给出了一个字符串或两个 {} 分隔的标记?

答案1

可以通过\def...#{...}功能来完成,以测试参数是否由内部开始{

\def\mymacro#1{\mymacroA#1{\end}{\end}\end}
\def\mymacroA#1#{%
   \ifx\end#1\end          % parameter begins by {
      \expandafter\mymacroB \else #1\expandafter\mymacroC
   \fi
}
\def\mymacroB#1#2#3\end{%
   \ifx\end#1\empty        % paremeter is empty
   \else\ifx\end#2\empty   % parameter has only one {}
      #1\else 1: #1 / 2: #2%
   \fi\fi
}
\def\mymacroC#1\end{}

A) \mymacro{Some text}        =   Some text 

B) \mymacro{{Some text}}      =   Some text 

C) \mymacro{{Text 1}{Text 2}} =   1: Text 1 / 2: Text 2

\bye

答案2

这是针对您的问题的一个完全可扩展的解决方案。我不知道您是否想经历这一切地狱。

\documentclass{article}

\makeatletter

\begingroup
  \catcode`{=12
  \global\let\bracetwelve={
\endgroup

\def\firsttoken#1#2\endfirsttoken{#1}

\def\ifelsefirstcharbrace#1{%
  \if\bracetwelve\expandafter\firsttoken\detokenize{#1}\relax\relax\endfirsttoken
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
}

\def\stripbracesrelax#1\relax{#1}

\makeatother

\def\mymacro#1{%
  \ifelsefirstcharbrace{#1}%
    {\domymacrotwo#1\relax\enddomymacrotwo}%
    {\domymacroone{#1}}}

\def\domymacroone#1{#1}

\def\domymacrotwo#1#2\enddomymacrotwo{%
  \ifx#2\relax
    \domymacroone{#1}%
  \else
    1: #1 / 2: \stripbracesrelax#2
  \fi}

\begin{document}
\ttfamily

\edef\x{\mymacro{}} \meaning\x

\edef\x{\mymacro{Some text}} \meaning\x

\edef\x{\mymacro{{Some text}}} \meaning\x

\edef\x{\mymacro{{Text 1}{Text 2}}} \meaning\x

\edef\x{\mymacro{{}{}}} \meaning\x
\end{document}

在此处输入图片描述


您可能想改用xparse

\documentclass{article}
\usepackage{xparse}

\DeclareDocumentCommand \mymacro { g g }
{%
  \IfValueT{#1}{\IfValueTF{#2}{1: #1 / 2: #2}{#1}}%
}

\begin{document}
\mymacro

\mymacro{Some text}

\mymacro{Some text}

\mymacro{Text 1}{Text 2}

\mymacro{}{}
\end{document}

在此处输入图片描述

相关内容