如何检测某些宏仅扩展为空字符串或空格?

如何检测某些宏仅扩展为空字符串或空格?

我需要检查几个宏,并且只有当它们的扩展名不为空也不仅为空格时才执行一些操作。

在伪代码中我看起来像这样

\if\macroToBeTested
    \doSomething
    \doSomethingElse
\fi

\doSomething并且仅当扩展为包含至少一个非空格字符\doSomethingElse时才执行。\macroToBeTested

我该如何实现呢?我更喜欢使用类似这样的方法

\if\test{\macroToBeTested}%
  \doSomething%
  \doSomethingElse%
\fi

而不是像这样

\test{\macroToBeTested}{%
  \doSomething%
  \doSomethingElse%
}

编辑

这是示例(伪代码)

\newcommand{\macroToBeTested}{   }%
Hello%
\if\test{\macro}%
  World!%
\fi

这将只打印“Hello”,而这个

\newcommand{\macroToBeTested}{  s }%
Hello%
\if\test{\macro}%
  World!%
\fi

应该打印“Hello World!”。

答案1

只需使用 D. Arsenau 提到的代码即可“条件”是包的名称吗?附加一个宏:

\makeatletter
{\catcode`\!=8 % funny catcode so ! will be a delimiter
 \catcode`\Q=3 % funny catcode so Q will be a delimiter
\long\gdef\given#1{88\fi\Ifbl@nk#1QQQ\empty!}
\long\gdef\blank#1{88\fi\Ifbl@nk#1QQ..!}% if null or spaces
\long\gdef\nil#1{\IfN@Ught#1* {#1}!}% if null
\long\gdef\IfN@Ught#1 #2!{\blank{#2}}
\long\gdef\Ifbl@nk#1#2Q#3!{\ifx#3}% same as above
}
\makeatother
\def\expblank{\expandafter\blank\expandafter} % additional macro

现在

\if\expblank{\mymacro}%
  <code if \mymacro expands only to zero or more spaces>%
\else
  <code if \mymacro expansion contains non space tokens>%
\fi

会做。

您可以类似地定义\expnil\expgiven

完整示例

\documentclass{article}
\makeatletter
{\catcode`\!=8 % funny catcode so ! will be a delimiter
 \catcode`\Q=3 % funny catcode so Q will be a delimiter
\long\gdef\given#1{88\fi\Ifbl@nk#1QQQ\empty!}
\long\gdef\blank#1{88\fi\Ifbl@nk#1QQ..!}% if null or spaces
\long\gdef\nil#1{\IfN@Ught#1* {#1}!}% if null
\long\gdef\IfN@Ught#1 #2!{\blank{#2}}
\long\gdef\Ifbl@nk#1#2Q#3!{\ifx#3}% same as above
}
\makeatother
\def\expblank{\expandafter\blank\expandafter}
\def\expgiven{\expandafter\given\expandafter}
\def\expnil{\expandafter\nil\expandafter}

\def\foo{ }
\def\bar{}
\def\baz{\bar}

\if\expgiven{\foo}
  \typeout{NOT BLANK}
\else
  \typeout{BLANK}
\fi

\if\expblank{\foo}
  \typeout{BLANK}
\else
  \typeout{NOT BLANK}
\fi

\if\expblank{\bar}
  \typeout{BLANK}
\else
  \typeout{NOT BLANK}
\fi

\if\expblank{\baz}
  \typeout{BLANK}
\else
  \typeout{NOT BLANK}
\fi

日志显示

BLANK
BLANK
BLANK
NOT BLANK

相关内容