引数に {} で区切られたトークンが多数含まれている場合、引数を飲み込む

引数に {} で区切られたトークンが多数含まれている場合、引数を飲み込む

1 つの引数と次の動作を持つマクロを実装するにはどうすればよいですか。 形式の引数、または のような 2 つのネストされた引数\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 つの文字列が指定されているか、{} で区切られた 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}

ここに画像の説明を入力してください

関連情報