
如何實現\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}