文件名字符串比较

文件名字符串比较

如果“\filename{XYZ-2100011}”和“\include{XYZ-2100011}”输入文件名不匹配,则需要显示编译错误。

例如,如果 \filename{ABC-2100012} 和 \include{XYZ-2100011} 字符串文件名都不同,则在编译时需要显示错误消息。

请找到以下 MWE 文件:

\documentclass{article}

\makeatletter
\def\filename#1{\gdef\@filename{#1}}

\def\include#1{\relax
  \ifnum\@auxout=\@partaux
    \@latex@error{\string\include\space cannot be nested}\@eha
  \else \@include#1 \fi}

\makeatother

\filename{XYZ-2100011}

\begin{document}

\include{XYZ-2100011}

\end{document} 

答案1

关键是使用 来\ifx比较字符串值。因此,对于\include,设置#1\@tmp宏中,然后\ifx\@filename\@tmp

而且,显然,我不主张重新定义像这样的核心宏\include,所以更改名称。

如果目标是避免文件名匹配,那么这样做:

\documentclass{article}

\makeatletter
\def\filename#1{\gdef\@filename{#1}}

\def\myinclude#1{\relax
  \def\@tmp{#1}%
  \ifx\@filename\@tmp
    \@latex@error{\string Duplicate filename}\@eha
  \else
    \ifnum\@auxout=\@partaux
      \@latex@error{\string\include\space cannot be nested}\@eha
    \else \@include#1 \fi
  \fi}

\makeatother

\filename{XYZ-2100011}

\begin{document}

\myinclude{XYZ-2100011}

\end{document} 

在此处输入图片描述

如果目标是强制文件名匹配,那么这样做:

\documentclass{article}

\makeatletter
\def\filename#1{\gdef\@filename{#1}}

\def\myinclude#1{\relax
  \def\@tmp{#1}%
  \ifx\@filename\@tmp
    \ifnum\@auxout=\@partaux
      \@latex@error{\string\include\space cannot be nested}\@eha
    \else \@include#1 \fi
  \else
    \@latex@error{\string Filenames don't match}\@eha
  \fi}

\makeatother

\filename{XYZ-2100011}

\begin{document}

\myinclude{XYZ-210x0011}

\end{document} 

在此处输入图片描述

相关内容