我尝试\date
使用l3regex
匹配传递给 的任何内容中的 4 个连续数字从命令中提取当前年份\date{ ... }
。但是,如果传入 ,我也想获取年份值\today
。
当手动输入日期时,下面的解决方案可以正常工作。
\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}
但是当\today
传递时,什么都没有匹配,大概是因为\regex_extract_all:nnN
对第二个参数不做任何处理。期待这问题和这源,我认为更改\regex_extract_all:nnN
为\regex_extract_all:nVN
或\regex_extract_all:nxN
会扩展\today
,但使用它会产生以下错误:
! 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
如果使用,我该如何解析值以\g_date_tl
获取年份?\today
答案1
您必须完全展开\today
,否则该字符串中将包含\today
。因此,您必须为 生成必要的变体\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}