Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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.

share|improve this question
1  
Have a look at experimental l3regex package. It provides regular expressions. –  Leo Liu Nov 28 '11 at 2:36

1 Answer 1

up vote 8 down vote accepted

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}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.