백슬래시가 포함된 대체 문자열

백슬래시가 포함된 대체 문자열

다음과 같이 문자열을 변환하는 함수를 만들어야 합니다.

Hello\textbackslash{}Bye

이것에:

Hello \\ Bye

StrSubstitute나는 성공하지 못한 채 (패키지에서 ) 사용해 보았습니다 xstring. 나는 다음과 같은 작업을 시도했습니다.

\newcommand{\TRANSFORM}[1]{\StrSubstitute{#1}{\textbackslash{}}{ \noexpand\\ }}

\TRANSFORM{Hello\textbackslash{}Bye}

답변1

일시적으로 의 의미를 재정의하여 \textbackslash다음과 같이 할 수 있습니다 \\.

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

\documentclass{article}

\newcommand{\TRANSFORM}[1]{{\let\textbackslash\\#1}}
\setlength{\parindent}{0pt}% Just for this example

\begin{document}

Hello\textbackslash{}Bye

\TRANSFORM{Hello\textbackslash{}Bye}

\end{document}

답변2

\noexpandarg모드를 사용해야 하므로 xstring인수 확장을 시도하지 않습니다.

\documentclass{article}
\usepackage{xstring}

%\noexpandarg % set \noexpandarg globally

\newcommand{\TRANSFORM}[1]{%
  \saveexpandmode\noexpandarg % set \noexpandarg locally
  \StrSubstitute{#1}{\textbackslash{}}{\\}%
  \restoreexpandmode % restore the previous mode
}

\begin{document}

\TRANSFORM{Hello\textbackslash{}Bye}

\end{document}

의 사용법에 따라 전역적으로 xstring설정할 수도 있습니다 \noexpandarg(관련 행에 주석 처리/주석 해제를 통해).

물론 이 경우 매크로를 재정의하는 것이 더 좋습니다.

\newcommand\TRANSFORM[1]{{% open a group
   \renewcommand{\textbackslash}[1]{\\}%
   #1%
}}

왜요 ?\renewcommand\let이 재정의도 삼키기 때문입니다 {}.

관련 정보