使用 xstring 检查 .tex 文件名

使用 xstring 检查 .tex 文件名

xtring我在检查 .tex 文件的文件名时遇到了困难。

下面显示的所有三种情况都产生了错误的输出。令人惊讶的是,在我实际更复杂的用法中,前两种情况工作得很好,所以我真的很困惑为什么我无法让这个简单的例子工作。以下内容需要保存为“FileName-AB.tex”,在我看来,它应该打印出语句的第一部分'If而不是else部分。

我想要检查文件名中破折号之间的部分。

\documentclass{article}
\usepackage{xstring}

\begin{document}

The .tex file name is "\jobname" \newline

% Check that the file name begins with "FileName-"
\IfBeginWith{\jobname}{FileName-}{
    Yes, file name does begin with [FileName]
}{
    Error: File name does NOT begin with [FileName]
}

% Check that the file name ends with "B"
\IfEndWith{\jobname}{-B}{
    Yes, file name ends with "B"
}{
    Error: File name does NOT end with [B]:
}

%Now check what that there is an "A" in between the dashes
\StrBetween[1,2]{\jobname}{-}{-}[\mystring]%
\IfStrEq{\mystring}{A}{
    Yes, file has an [A] in the middle
}{
    Error: File name does NOT have an [A] in the middle,
it has [\mystring] instead.
}

\end{document}

答案1

\jobname命令返回 12 个 catcode 字符和 10 个 catcode 空格。您必须先对参数进行去标记化,然后才能对其进行操作以xstring匹配 catcode。这可以在命令*后使用“ ”来完成xstring(阅读手动的进一步解释如下):

\documentclass{article}
\usepackage{xstring}

\begin{document}

The .tex file name is "\jobname" \newline

% Check that the file name begins with "FileName-"
\IfBeginWith*{\jobname}{FileName-}{
    Yes, file name does begin with [FileName]
}{
    Error: File name does NOT begin with [FileName]
}

% Check that the file name ends with "B"
\IfEndWith*{\jobname}{-B}{
    Yes, file name ends with "B"
}{
    Error: File name does NOT end with [B]:
}

%Now check what that there is an "A" in between the dashes
\StrBetween*[1,2]{\jobname}{-}{-}[\mystring]%
\IfStrEq*{\mystring}{A}{
    Yes, file has an [A] in the middle
}{
    Error: File name does NOT have an [A] in the middle,
it has [\mystring] instead.
}
\end{document}

答案2

返回的字符串\jobname使用 catcode其他对于所有字符,包括字母,但空格除外,这些字符仍在 catcode 中空间。大多数字符串比较代码也会比较 catcode,因此即使 ASCII 内容相同,测试也不会成立。

在进行比较之前,您可以\@onelevel@sanitize\somestring先设置 catcode 。\somestring\jobname

相关内容