{}로 구분된 토큰이 많이 포함된 경우 인수를 삼키기

{}로 구분된 토큰이 많이 포함된 경우 인수를 삼키기

하나의 인수와 다음 동작을 사용하여 매크로를 어떻게 구현할 수 있습니까 \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}

여기에 이미지 설명을 입력하세요

관련 정보