为文本着色时自动跳过标点符号

为文本着色时自动跳过标点符号

我想在给文本着色时自动跳过标点符号。目前我的解决方案是手动给文本着色,但对于标点符号较多的长篇文章来说,这样做不太优雅。我不需要所有的单词都是红色的,但各种颜色都是可以的。

\documentclass{article}
\usepackage{xcolor}
\begin{document}
    
    {\color{red}{This is a text}}, {\color{red}{this is a text}}, {\color{red}{this is a text}}! {\color{red}{This is a text}}, {\color{red}{this is a text}}.
    
\end{document}


在此处输入图片描述

答案1

expl3 regex 正则表达式可以进行标点符号。

这里,在一个专用的彩色环境中:

黑色标点

平均能量损失

\documentclass{article}
\usepackage{xcolor}
\usepackage{xparse}

\ExplSyntaxOn



\NewDocumentEnvironment { punct }  { o +b } {
    \IfNoValueTF {#1}
         {      
                \color{red}
        }
     {      
                \color{#1}
        }
        \tl_set:Nn
                    \l_tmpa_tl
                    { #2 }
\regex_replace_all:nnN 
            { [[:punct:]] } % POSIX punctuation set
            { 
                    \cB\{ \c{color}\cB\{ black \cE\} \0 \cE\} 
                    } 
            \l_tmpa_tl
            
        \tl_use:N
                    \l_tmpa_tl
}{}

\ExplSyntaxOff


\begin{document}
Outside environment:

This is a text, this is a text, this is a text! This is a text, this is a text.

\begin{punct}
Inside environment:

This is a text, this is a text, this is a text! This is a text, this is a text.

\end{punct}

\begin{punct}[blue]
Inside environment:

This is a text, this is a text, this is a text! This is a text, this is a text.

\end{punct}

\end{document}


如果命令与文本混合在一起,情况就会变得更加复杂。

示例:使用自由格式的颜色和格式,并且\{并且}不算作标点符号:

文本和命令

平均能量损失

\documentclass{article}
\usepackage{xcolor}
\usepackage{xparse}

\ExplSyntaxOn



\NewDocumentEnvironment { punct }  { +b } {
        \tl_set:Nn
                    \l_tmpa_tl
                    { #1 }

\regex_replace_all:nnN 
            { [\.\,\;\:\!\?] } % 
            { 
                    \cB\{ \c{color}\cB\{ black \cE\} \0 \cE\} 
                    } 
            \l_tmpa_tl
            
        \tl_use:N
                    \l_tmpa_tl
}{}

\ExplSyntaxOff

\newcommand\test{\color{red}This is a text, this \color{green} is a text, this is a text! This \color{brown} \textit{is a text, this} is a text.}

\begin{document}
Outside environment:

\color{red}This is a text, this \color{green} is a text, this is a text! This \color{brown} \textit{is a text, this} is a text.

\begin{punct}
Inside environment:


\color{red}This is a text, this \color{green} is a text, this is a text! This \color{brown} \textit{is a text, this} is a text.

\end{punct}


\end{document}

答案2

您可以使标点符号活跃并将其定义为黑色,但我不会这样做:必然会出现一些问题。

如果不是使每个文本都变成红色,而是使所有内容都变成红色,然后只需在本地将标点符号设置为黑色,则可以大大简化标记。

\documentclass{article}
\usepackage{xcolor}
\newcommand\B{\textcolor{black}}
\begin{document}
    
{\color{red}
This is a text\B, this is a text\B, this is a text\B! This is a text\B, this is a text\B.

}
    
\end{document}

相关内容