Here's a LuaLaTeX-based solution. (Lua has a very powerful string manipulation library.) The answer sets up a LaTeX macro called \StringBefore
, which calls a Lua function that does the actual work. The macro \StringBefore
is expandable; it can be made the argument of some other macro, as is done in the code below. Incidentally, I'm assuming that if the character(s) in the second argument aren't found in the search string, nothing should be returned.
% !TeX program = lualatex
\documentclass{article}
\usepackage{luacode} % for "\luastringN" macro and "luacode" env.
\begin{luacode}
function string_before ( str, patt )
n = string.find ( str, patt )
if n then -- string.find made (at least) one match...
tex.sprint ( string.sub ( str, 1, n-1) )
else -- no match -> print nothing
tex.sprint ( "" )
end
end
\end{luacode}
\newcommand\StringBefore[2]{\directlua{
string_before(\luastringN{#1},\luastringN{#2})}}
\begin{document}
\StringBefore{aaa {\bfseries bbb} ccc;some other text}{;}
\newcommand{\temp}{\StringBefore{ddd {\bfseries eee} \emph{ggg} hhh;dummy text}{;}}
\temp
\StringBefore{aaa {\bfseries bbb} ccc;some other text}{u} % no match
zzz
\end{document}
\bfseries
doesn't fix the problem, so I guess that the problem lies elsewhere.\bfseries
and[temp]
or removing\bfseries
and changing[temp]
to[\temp]
works though.