比较从 Jobname 中提取的字符串

比较从 Jobname 中提取的字符串

我有一些解析的代码\jobname,但它没有按预期工作。我在下面提供了一个最小示例,其中文件名为HelloWorld.tex。当我打印时,它显示为“HelloWorld”。当我使用例如's\jobname将它与字符串“HelloWorld”进行比较时,它们不相等。为什么?xstring\IfStrEq

我在 OSX 上运行的是 TeX Live 的 MacTeX 版本。

\documentclass{article}
\usepackage{xstring}

\begin{document}
\noindent
.HelloWorld.\\
.\jobname.\\
\IfStrEq{\jobname}{HelloWorld}{Yes}{No}\\

\end{document}

编译后的输出为

。你好世界。

。你好世界。

答案1

\jobname语是 TeX 字符串,因此所有字符的类别代码均为 12(其他),而不是 11(字母)(空格除外,空格的类别代码为 10(空格))。有点令人困惑的是,xstring这里进行的是基于标记的比较,而不是字符串比较!假设 e-TeX 可用,您可以轻松修复代码

\documentclass{article}
\usepackage{xstring}

\begin{document}
\noindent
.HelloWorld.\\
.\jobname.\\
\IfStrEq{\jobname}{\detokenize{HelloWorld}}{Yes}{No}\\

\end{document}

还有其他选择。例如,除了 Knuth 的 TeX 之外,任何最新的 TeX 引擎都可以直接进行字符串比较

\documentclass{article}
\usepackage{pdftexcmds}

\begin{document}
\noindent
.test.\\
.\jobname.\\
\makeatletter
\ifnum\pdf@strcmp{\jobname}{HelloWorld}=0 Yes\else No\fi
\makeatother

\end{document}

坚持使用经典 TeX,可以通过使用来设置比较,\meaning以对宏的内容进行去标记。这在 LaTeX 中可用,如下所示\@onelevel@sanitize

\documentclass{article}

\begin{document}
\noindent
.test.\\
.\jobname.\\
\makeatletter
\edef\@tempa{\jobname}
\def\@tempb{HelloWorld}
\@onelevel@sanitize\@tempb
\ifx\@tempa\@tempb Yes\else No\fi
\makeatother
\end{document}

答案2

我刚刚意识到还有另一种简单的解决方案。该xstring软件包的比较命令带有星号,不考虑类别代码。要使文件正常工作,只需将其替换\IfStrEq\IfStrEq*

相关内容