如何替换文本

如何替换文本

我想写一些类似的东西:

\replace{Text should be replaced here, here and here}{here}{Latex}

它应该输出

文本应替换为 Latex、Latex 和 Latex

如何才能做到这一点?

答案1

仅替换完整单词的复杂解决方案:

\documentclass{article}
%\usepackage{xparse,l3regex}% remove with recent LaTeX releases

\ExplSyntaxOn
\NewDocumentCommand{\replace}{mmm}
 {
  \marian_replace:nnn {#1} {#2} {#3}
 }

\tl_new:N \l_marian_input_text_tl
\tl_new:N \l_marian_search_tl
\tl_new:N \l_marian_replace_tl

\cs_new_protected:Npn \marian_replace:nnn #1 #2 #3
 {
  \tl_set:Nn \l_marian_input_text_tl { #1 }
  \tl_set:Nn \l_marian_search_tl { #2 }
  \tl_set:Nn \l_marian_replace_tl { #3 }
  \regex_replace_all:nnN { \b\u{l_marian_search_tl}\b } { \u{l_marian_replace_tl} } \l_marian_input_text_tl
  \tl_use:N \l_marian_input_text_tl
 }
\ExplSyntaxOff

\begin{document}

\replace{Text should be replaced here, here and here}{here}{\LaTeX{}}

\replace{Text should be replaced here, here and not there}{here}{\LaTeX{}}

\end{document}

在此处输入图片描述

一个更简单的解决方案,可以替换所有出现的情况:

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\replace}{mmm}
 {
  \marian_replace:nnn {#1} {#2} {#3}
 }

\tl_new:N \l_marian_input_text_tl

\cs_new_protected:Npn \marian_replace:nnn #1 #2 #3
 {
  \tl_set:Nn \l_marian_input_text_tl { #1 }
  \tl_replace_all:Nnn \l_marian_input_text_tl { #2 } { #3 }
  \tl_use:N \l_marian_input_text_tl
 }
\ExplSyntaxOff

\begin{document}

\replace{Text should be replaced here, here and here}{here}{\LaTeX{}}

\replace{Text should be replaced here, here and not there}{here}{\LaTeX{}}

\end{document}

在此处输入图片描述

答案2

在此处输入图片描述

\def\replace#1#2#3{%
 \def\tmp##1#2{##1#3\tmp}%
   \tmp#1\stopreplace#2\stopreplace}
\def\stopreplace#1\stopreplace{}

\replace{Text should be replaced here, here and here}{here}{Latex}

\bye

以纯文本形式编写,但也可以在乳胶中使用。

答案3

这使用包StrSubstitute中的高级宏。用作第一个可选参数来替换xstring[0]全部的出现here,但正如 egreg 在评论中所说,它也会取代像where或这样的词there

\documentclass{article}

\usepackage{xstring}




\begin{document}

\StrSubstitute[0]{Text should be replaced here, here and here}{here}{Latex}
\end{document}

在此处输入图片描述

答案4

OpTeX 提供了宏\replstring\macro{from}{to}。例如:

\def\replace#1#2#3{\def\tmp{#1}\replstring\tmp{#2}{#3}\tmp}

\replace{Text should be replaced here, here and here}{here}{\OpTeX}

\replace{Text should be replaced here, here and not there}{here}{\OpTeX}

\bye

印刷:

文本应替换为 OpTEX、OpTEX 和 OpTEX

文本应替换为 OpTEX、OpTEX 而不是 tOpTEX

相关内容