Based on this answer, I am trying to define a newcases environment that automatically expands "if" into ", \quad & \text{if }" and expands "otherwise" into ", \quad & \text{otherwise}".
My code and the output are included below. As you can see in the output, the result is incorrect with \geq, \\, and \empty rendered literally and fl inserted at each line break in the code.
\documentclass{article}
\usepackage{filecontentsdef}
\usepackage{amsmath}
\ExplSyntaxOn
\cs_generate_variant:Nn \tl_replace_all:Nnn {Nx}
\NewDocumentEnvironment {newcases} {} {
% Use filecontentsdef to store everything until "\endfilecontentsdefmacro"
% into a macro named "\l__envcontents_tmp_tl".
\filecontentsdefmacro \l__envcontents_tmp_tl
} {
\endfilecontentsdefmacro
\str_set:NV \l__envcontents_tmp_tl \l__envcontents_tmp_tl
\tl_replace_all:Nxn \l__envcontents_tmp_tl
{ \c_space_tl\tl_to_str:n{if} \c_space_tl} % Search
{, \quad & \text{if~}} % Replace
\tl_replace_all:Nxn \l__envcontents_tmp_tl
{\tl_to_str:n{otherwise}} % Search
{, \quad \text{otherwise}} % Replace
% Output the result.
\left\{\begin{array}{ll}
\l__envcontents_tmp_tl
\end{array}\right.
}
\ExplSyntaxOff
\begin{document}
Desired output:
\begin{equation}
\begin{cases}
a, \quad & \text{if } a \geq 0, \
-a, \quad & \text{otherwise}.
\end{cases}
\end{equation}
Actual output, using newcases environment:
\begin{equation}
\begin{newcases}
a if a \geq 0 \
-a otherwise.
\end{newcases}
\end{equation}
\end{document}


ifwill be used? – projetmbc Aug 16 '23 at 19:36&, so I'd like to not explicitly write&. Thecases*environment looks useful, but I'd still like to define the environment I described, partially as a way of better understandexpl3syntax. – Paul Wintz Aug 16 '23 at 19:47ifs. – Paul Wintz Aug 16 '23 at 19:47