# Expand \date with l3regex

I'm trying to extract the current year from the \date command using l3regex to match 4 consecutive numbers from whatever is passed to \date{ ... }. However, I also want to get the year value if one passes in \today.

My solution below works fine when a date is entered manually.

\documentclass{report}

\usepackage{expl3, xparse}

\ExplSyntaxOn
\seq_new:N  \g_year_seq % Sequence to store the match from regex
\tl_new:N   \g_year_tl  % Token list to store the year
\tl_new:N   \g_date_tl  % Token list to store the full date

%% Re-define \date to store value in a tokenlist
\RenewDocumentCommand\date{ m }
{
\tl_gset:Nn \g_date_tl {#1}
\regex_extract_all:nnN {(\d{4})} {#1} \g_year_seq
\tl_gset:Nn \g_year_tl {\seq_item:Nn \g_year_seq {1}}
}

\NewDocumentCommand\printdate{ }
{
The~date~is:~\g_date_tl \par
The~year~is:~\g_year_tl
}

\ExplSyntaxOff

%% Set the date
% \date{August, 2017} %% Works like a charm
% \date{\today} %% Doesnt work

\begin{document}
\printdate
\end{document}


But when \today is passed, nothing is matched, presumably because \regex_extract_all:nnN does nothing with the second parameter. Looking to this question and this source, I would think that changing \regex_extract_all:nnN to \regex_extract_all:nVNor \regex_extract_all:nxN would expand \today, but using it produces the following error:

! Undefined control sequence.
\date code ..._date_tl {#1}\regex_extract_all:nVN
{(\d {4})}#1\g_year_seq \t...
l.28 \date{\today}
%% Doesnt work


How can I parse the value of \g_date_tl to get the year if \today is used?

• Note that your variable names should use a distinctive prefix e.g. \g_hatsvi_year_seq rather than \g_year_seq, which is much more likely to cause trouble. Also, xparse creation commands should wrap internal functions and just provide a user interface, but not really do anything themselves. – cfr Aug 7 '17 at 3:34

You have to fully expand \today, otherwise there will be literally \today inside that string. Therefore you have to generate the necessary variant for \regex_extract_all:nnN.

\documentclass{report}

\usepackage{expl3, xparse}

\ExplSyntaxOn
\seq_new:N  \g_year_seq % Sequence to store the match from regex
\tl_new:N   \g_year_tl  % Token list to store the year
\tl_new:N   \g_date_tl  % Token list to store the full date

\cs_generate_variant:Nn \regex_extract_all:nnN { nx }

%% Re-define \date to store value in a tokenlist
\RenewDocumentCommand\date{ m }
{
\tl_gset:Nx \g_date_tl {#1}
\regex_extract_all:nxN {(\d{4})} {#1} \g_year_seq
\tl_gset:Nn \g_year_tl {\seq_item:Nn \g_year_seq {1}}
}

\NewDocumentCommand\printdate{ }
{
The~date~is:~\g_date_tl \par
The~year~is:~\g_year_tl
}

\ExplSyntaxOff

%% Set the date
\date{\today}

\begin{document}
\printdate
\end{document}