How to access the matched of a regular expression in \regex_extract_once

l3regexlatex3regular expressions

This time I have a function that takes strings and shall test whether the color given after the last dash is in a given set of colors or not. While I am able to design a regular expression for it, it seems I am too stupid to access the results, that I expected to be stored in l_IconAndColor_seq.

\documentclass{standalone}

\ExplSyntaxOn

\NewDocumentCommand{\ColorNameChopper}{m}
{
    \my_colornamechopper:n { #1 }
}

\seq_new:N \l_IconAndColor_seq

\cs_new:Nn \my_colornamechopper:n
{
    #1: & \regex_extract_once:nnNTF 
    {\A(.*)-(Black|White)\Z}
     {#1}
     \l_IconAndColor_seq
     {TRUE & \seq_item:Nn \l_IconAndColor_seq {2} & \seq_item:Nn 
     \l_IconAndColor_seq {3} & 
     \seq_count:N \l_IconAndColor_seq}
     {FALSE}\\
}

\ExplSyntaxOff

\begin{document}
    \begin{tabular}{lllll}
    String & Found & First & Second & Size\\
    \ColorNameChopper{Test-Black}
    \ColorNameChopper{Test-White}
    \ColorNameChopper{Test-Orange}
    \end{tabular}
\end{document}

I am probably struggling of something simple, but I can't see it and so long the sequence is empty:

enter image description here

Best Answer

You're setting the sequence in a table cell and try to use it in another one.

Besides, you want to use the last item in the sequence.

The first problem can be solved by expanding the contents prior to using it. The other one is solved by using item –1

\documentclass{article}

\ExplSyntaxOn

\NewDocumentCommand{\ColorNameChopper}{m}
  {
    \tobibs_colornamechopper:n { #1 }
  }

\seq_new:N \l__tobibs_colornamechopper_seq

\cs_new_protected:Nn \tobibs_colornamechopper:n
  {
    #1: &
     \regex_extract_once:nnNTF {(.*)-(Black|White)} {#1} \l__tobibs_colornamechopper_seq
       {
         \use:e
           {
             TRUE &
             \seq_item:Nn \l__tobibs_colornamechopper_seq {-2} &
             \seq_item:Nn \l__tobibs_colornamechopper_seq {-1} &
             \seq_count:N \l__tobibs_colornamechopper_seq
           }
       }
       {FALSE}
    \\
  }

\ExplSyntaxOff

\begin{document}

\begin{tabular}{lllll}
String & Found & First & Second & Size\\
\ColorNameChopper{Test-Black}
\ColorNameChopper{Test-White}
\ColorNameChopper{Test-Orange}
\ColorNameChopper{Test-again-Black}
\end{tabular}

\end{document}

enter image description here

How and why does it work? First of all, your command \regex_extract_once:nnNTF sets the sequence in a table cell, so as soon as TeX processes & (when typesetting), the value would be lost.

However, if we build the whole table row before processing it, the value would not be lost (expansion takes place at a different level than typesetting, so TeX will not “see” the &, as it's just expanding macros and still not building the table. Yes, tables are quite hard to manage.