expl3 test if a string starts with a given prefix
Karl Berry <[email protected]> Sat, 15 Nov 2025 10:24:49 -0700
| Newsgroups | gmane.comp.tex.texhax |
|---|---|
| Message-ID | <[email protected]> |
Using expl3, I'd like to test if a given "string" (argument) starts with
a given prefix, namely "http://". For a prefix of a given length, 7 in
my case, I guess the idea is to extract the first 7 tokens using
str_range and then compare them with \str_if_eq? But I cannot get the
details right. Here's my best attempt (with help from various bots). Is
it at all close?
\documentclass{article}
\begin{document}
\ExplSyntaxOn
\cs_new:Npn \astr_if_starts_with:nnTF #1#2
{
% #1 = prefix to test
% #2 = full string
\str_if_eq:nnTF
{ \str_range:nnn {#2} {1} { \str_count:n {#1} } }
{ #1 }
}
\str_if_starts_with:nnTF {abc} {abcdef}
{ \message{prefix} }
{ \message{notprefix} }
\end{document}
This feels like an easy expl3 programming question, but evidently I've
failed to grok interface3.pdf.
FWIW, the real context is this, from tugboat.dtx (with thanks to
Ulrike):
\def\tbsurl@#1
{
\str_set:Nn\l_tmpa_str{#1}
\str_if_in:NnTF \l_tmpa_str {http://}
... % an http:// url
where I need to replace \str_if_in with some other function that checks
if http:// is only the *beginning* of \l_tmpa_str, not anywhere within
it. Because archive.org routinely embeds "http://" in their urls,
e.g., https://web.archive.org/web/20090809184749/http://www.eco-log.de/
Thanks,
Karl