如何在带下划线 href 的 URL 中使用数字符号 (#)

如何在带下划线 href 的 URL 中使用数字符号 (#)

这个问题很简短:如何使用数字符号#) 在带下划线的 URL 中href

\documentclass{article}

\usepackage{hyperref}

\begin{document}

1 (without \#, link, underlined) = \underline{\href{http://the-best-URL-in-the-world_without-a-number-sign}{URL without number sign}}

% Un-comment the line below to see the error
2 (with \#, link, underlined) = % \underline{\href{http://the-best-URL-in-the-world_with-a-number-sign-#}{URL with a number sign}}

% For reference, the following works fine
3 (with \#, link, not underlined) = \href{http://the-best-URL-in-the-world_with-a-number-sign-#}{URL with a number sign}

\end{document}

取消注释指定的位置以查看编译错误。

PS:这个问题可能类似于如何使用 \endnotes 包在 URL 中包含 # 符号

答案1

以下是\uhref选择性地为文本加下划线的命令:

\documentclass{article}
\usepackage{etoolbox}
\usepackage{hyperref}

\makeatletter
\newif\ifunderlinehref
\DeclareRobustCommand{\uhref}{\underlinehreftrue\href}
\patchcmd{\hyper@link@}
  {{\Hy@tempb}{#4}}
  {{\Hy@tempb}{\ifunderlinehref\underline{#4}\else#4\fi}}
  {}{}
\apptocmd{\hyper@link@}
  {\aftergroup\underlinehreffalse}
  {}{}
\makeatother

\begin{document}

\href{http://tex.stackexchange.com/#/!!!}{URL with a number sign}

\uhref{http://tex.stackexchange.com/#/!!!}{URL with a number sign}

\end{document}

在此处输入图片描述

如果您希望所有链接都带有\href下划线,则可以使用更简单的补丁:

\documentclass{article}
\usepackage{etoolbox}
\usepackage{hyperref}

\makeatletter
\patchcmd{\hyper@link@}
  {{\Hy@tempb}{#4}}
  {{\Hy@tempb}{\underline{#4}}}
  {}{}
\makeatother

\begin{document}

\href{http://tex.stackexchange.com/#/!!!}{URL with a number sign}

\end{document}

在此处输入图片描述

答案2

好吧,解决这个问题的一种方法是改变 的位置,\underline使其位于 的第二个参数内href。那么答案就变成了:

\documentclass{article}

\usepackage{hyperref}

\begin{document}

1 (without \#, link, underlined) = \underline{\href{http://the-best-URL-in-the-world_without-a-number-sign}{URL without number sign}}

% Fixed below
2 (with \#, link, underlined) = \href{http://the-best-URL-in-the-world_with-a-number-sign-#}{\underline{URL with a number sign}}

3 (with \#, link, not underlined) = \href{http://the-best-URL-in-the-world_with-a-number-sign-#}{URL with a number sign}

\end{document}

相关内容