# Why does xstrings \StrBefore work, but not \IfBeginWith?

I'm currently using the package showkeys to debug the labels in my document. Using the command \renewcommand{\showkeyslabelformat}[1]{...} one can customise the display of the labels. I want to handle equation labels (labels that start with eq:) differently than other labels. Therefore, I wanted to test whether the label starts with eq using xstring. Somehow this does not seem to work.

Here is a minimal working example:

\documentclass{article}

\usepackage{amsmath}
\usepackage{showkeys}
\usepackage{xstring}

\begin{document}

% FIRST BLOCK
\renewcommand*\showkeyslabelformat[1]{%
\fbox{\small\ttfamily\StrBefore{#1}{:}}}

\textbf{Lemma.} \label{lemma:no_equation}
$$\label{eq:my_equation} \sum_{i=0}^\infty 2^{-1} = 2$$

% SECOND BLOCK
\renewcommand*\showkeyslabelformat[1]{%
\fbox{\small\ttfamily\IfBeginWith{#1}{eq}{equation}{no equation}}}

\textbf{Lemma.} \label{lemma:no_equation}
$$\label{eq:my_equation} \sum_{i=0}^\infty 2^{-1} = 2$$
\end{document}


The output looks like this:

As you can see, xstring is able to correctly parse the first part of the labels. Still it does not work to condition on the beginning of the string. What am I missing here?

Regular expressions in expl3 are category code agnostic.

\documentclass{article}

\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{showkeys}

\newtheorem{lemma}{Lemma}

\ExplSyntaxOn
\NewDocumentCommand{\beginwithTF}{mmmm}
{% #1 = string to search in, #2 = string to search, #3 = true, #4 = false
\regex_match:nnTF { \A #2\: } { #1 } { #3 } { #4 }
}
\ExplSyntaxOff

\renewcommand*\showkeyslabelformat[1]{%
\fbox{\small\ttfamily\beginwithTF{#1}{eq}{equation}{no equation}}}

\begin{document}

\begin{lemma} \label{lemma:B}
$$\label{eq:B} \sum_{i=0}^\infty 2^{-1} = 2$$
\end{lemma}

\end{document}


With \regex_match:nnTF we look whether the given regular expression (first argument) matches the given string (second argument). I've kept the order of arguments in \IfBeginWith, though.

• Thank you! I also found out, that the starred macros in xstring do not take the catcodes into account. Therefore the original \IfBeginWith can just be replaced by the starred version. Jan 26 at 18:45

showkeys makes things safe with \meaning so that labels with & or \$ or other special character do not blow up when typeset. so you are comparing catcode 12 ("other") eq with catcode 11 (letter) eq and these are not equal.

• Thanks, I see the problem. Do you see a workaround here? Jan 26 at 16:12
• you could use a catcode 12 eq as your test or use \pdfstrcmp (which does catcode-ignored comparisons or ....) Jan 26 at 16:36
• Thank you! I also found out, that the starred macros in xstring do not take the catcodes into account. Therefore the original \IfBeginWith can just be replaced by the starred version. Jan 26 at 18:45