The problem is that \currfilename
returns a “stringified” file name; in TeXnical terms, all characters have category code 12. However, the characters Ch
you are supplying in the second optional argument have category code 11, so there's no match.
One possibility is to use the *
-variant of \StrBetween
, that applies \detokenize
to all mandatory arguments (after full expansion), so also Ch
become category code 12 and the match is found.
Another possibility is to use l3regex
.
\documentclass{article}
\usepackage{currfile,xparse,l3regex}
\ExplSyntaxOn
\NewDocumentCommand{\extractnumber}{o}
{
\IfNoValueTF{#1}
{
\mathxlv_extract_number:N \l_tmpa_tl
\tl_use:N \l_tmpa_tl
}
{
\mathxlv_extract_number:N #1
}
}
\cs_new_protected:Nn \mathxlv_extract_number:N
{
\tl_set_eq:NN #1 \currfilename
\regex_replace_once:nnN { \A Ch ([^-]*) .* \Z } { \1 } #1
}
\ExplSyntaxOff
\begin{document}
\extractnumber
\extractnumber[\thisfilenumber]
\texttt{\meaning\thisfilenumber}
\end{document}
If the document is named Ch2-2nde.tex
, the output is

If the document is named Ch14-abc-def.tex
, the output is

\currfilename
returns characters with category code 12, that don't matchCh
of category code 11. The solution by @SunilkumarKS works because the*
variant applies\detokenize
(after full expansion) and soCh
is transformed in category code 12 characters.