
次のような文字列を変換する関数を作成する必要があります。
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
? この再定義は も飲み込むからです{}
。