TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
Have a look at experimental l3regex package. It provides regular expressions. – Leo Liu Nov 28 '11 at 2:36
up vote 8 down vote accepted

With l3regex


  \str_set:Nn \l_temp_str {#1}
  \regex_replace_all:nnN {#2} {#3} \l_temp_str
\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
share|improve this answer

Your Answer


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.