\href 內的宏擴展

\href 內的宏擴展

我想建立一個快捷方式

\href{tel:0123456789}{01\,23\,45\,67\,89}

我可以\StrSubstitutexstring包中使用

\StrSubstitute{01 23 45 67 89}{ }{\,}

在 的第二個參數內href。但同樣的事情與

\StrSubstitute{01 23 45 67 89}{ }{}

在第一個參數是行不通的。

我想,我明白這是巨集展開順序的問題。但是我怎麼能讓 LaTeX 首先擴展\StrSubstitute成可以解析的字串\href呢?

這是我真正想要實現的目標的一個最小範例:

\documentclass{minimal}

\usepackage{xstring}
\usepackage{hyperref}

\newcommand\phone[1]{\href{tel:\StrSubstitute{#1}{ }{}}{\StrSubstitute{#1}{ }{\,}}}

\begin{document}

    \href{tel:0123456789}{01\,23\,45\,67\,89}

    \href{\StrSubstitute{01 23 45 67 89}{ }{}}{\StrSubstitute{01 23 45 67 89}{ }{\,}}

    \phone{01 23 45 67 89}

\end{document}

編輯:成對模式並不重要,因為不同的國家有不同的數位格式約定。我真的只想替換/刪除空格(也許還有其他東西)。

答案1

展開字串替換第一的透過將其儲存在一個參數中,然後您可以將其與hyperref\href

\documentclass{article}

\usepackage{xstring}
\usepackage{hyperref}

\newcommand\phone[1]{%
  \StrSubstitute{#1}{ }{}[\firstarg]% Store first substitution in \firstarg
  \StrSubstitute{#1}{ }{\,}[\secondarg]% Store second substitution in \secondarg
  \href{tel:\firstarg}{\secondarg}% Use stored arguments in \href
}

\begin{document}

\href{tel:0123456789}{01\,23\,45\,67\,89}

\phone{01 23 45 67 89}

\end{document}

答案2

這些xstring命令不可擴展,因此通常不能在其他命令中內聯使用。您可以在此處使用簡單的可擴展替代品。

\documentclass{minimal}


\usepackage{hyperref}

\makeatletter
\def\zza#1 {#1\zza}
\def\zzb#1 {#1\,\zzb}
\newcommand\phone[1]{{\def\!##1{}\def\$##1##2{}\href{tel:\zza#1\! }{\zzb#1\$ }}}
\makeatother

\begin{document}

    \href{tel:0123456789}{01\,23\,45\,67\,89}

    \phone{01 23 45 67 89}

\end{document}

答案3

您不能\StrSubstitute在這些地方使用,因為它不會在替換後產生字串,而是產生一組相當複雜的指令來產生該字串。

一個更複雜的解決方案,可以避免在數字對之間輸入空格,因此即使您忘記了它們也可以工作。

\documentclass{article}

\usepackage{xparse}
\usepackage{hyperref}

\ExplSyntaxOn

\NewDocumentCommand{\phone}{m}
 {
  \dlichti_phone:n { #1 }
 }

\tl_new:N \l_dlichti_phone_href_tl
\tl_new:N \l_dlichti_phone_print_tl

\cs_new_protected:Nn \dlichti_phone:n
 {
  \tl_set:Nx \l_dlichti_phone_href_tl { #1 }
  % remove all spaces
  \tl_replace_all:Nnn \l_dlichti_phone_href_tl { ~ } { }
  % save a copy
  \tl_set_eq:NN \l_dlichti_phone_print_tl \l_dlichti_phone_href_tl
  % insert a thin space between any pair of digits
  \regex_replace_all:nnN
   { ([0-9][0-9]) } % two digits followed by another digit
   { \1\c{,} } % the same with \, in between
   \l_dlichti_phone_print_tl
  % remove the trailing \,
  \regex_replace_once:nnN { \c{,} \Z } { } \l_dlichti_phone_print_tl
  \dlichti_phone_href:VVV
   \c_colon_str
   \l_dlichti_phone_href_tl
   \l_dlichti_phone_print_tl
 }
\cs_new_protected:Nn \dlichti_phone_href:nnn
 {
  \href{tel#1#2}{#3}
 }
\cs_generate_variant:Nn \dlichti_phone_href:nnn { VVV }

\ExplSyntaxOff

\begin{document}

\phone{01 23 45 67 89}

\phone{0123456789}

\end{document}

在此輸入影像描述

相關內容