5

Using StrSubstitute from xstring I can find and replace matches. For e.g.:

\StrSubstitute{I like to eat fish.}{fish}{apples} gives "I like to eat apples."

\StrSubstitute{Do you want to eat?}{eat}{fly} gives "Do you want to fly?"

  • How can I adjust this so that the replace only occurs when the matching string not bounded by letters or numbers?

For e.g., when replacing "fish" with "apples":

I like to eat fish. gives "I like to eat apples." (changed)

I like to go fishing. gives "I like to go fishing." (not changed)

@fish are interesting/. gives "@apples are interesting." (changed)

9fish is too many. gives "9fish is too many." (not changed)

In the above cases, the changes did not occur in situations when the letters (A-Z or a-z) or number (0|+) appeared on either side.

Village
  • 13,603
  • 23
  • 116
  • 219

1 Answers1

8

With l3regex

\documentclass{article}

\usepackage{l3regex}
\ExplSyntaxOn
\newcommand\replaceall[3]{
  \str_set:Nn \l_temp_str {#1}
  \regex_replace_all:nnN {#2} {#3} \l_temp_str
  \l_temp_str
}
\ExplSyntaxOff
\begin{document}
\replaceall{foo and foo and afoo and foo0 and 123foo123 and foo}{(\W|^)foo(\W|$)}{\1bar\2}
% result:
% bar and bar and afoo and foo0 and 123foo123 and bar
\end{document}
Leo Liu
  • 77,365