# How to do search-and-replace in a macro?

Is it possible to let (La)TeX search and replace text in a macro during compile time? For example, given

\newcommand{\sometext}{a b c d e f g}


I'd like to have something like

\searchreplace{\sometext}{b c}{x

y}


that would result in

a x

y d e f g


Ideally this would work with replacing macros, like

\searchreplace{hi {\itshape there}}{\itshape}{\bfseries}


that then would produce (and interpret)

hi {\bfseries there}

• First, I know that this is only an example, but please do not ever use \bf or \it in LaTeX---use \bfseries and \itshape. Second, do you mean something like what the package xpatch does? ctan.org/pkg/xpatch – yo' Aug 30 '15 at 5:55
• There seems little benefit when supplying something verbatim that requires a change; the question there would be "Why not just change whatever you want right there...?". It's more likely you'd like to search-and-replace inside something "unknown" like a macro. That's a major difference between your first and second examples. – Werner Aug 30 '15 at 6:02
• yo - I changed the example. Maybe I tried to make it too short :) – TeXter Aug 30 '15 at 7:19
• Werner - The original macro is sourced from another file I do not have under control, and that needs minimal tweaks when used in multiple other files. Otherwise I would have asked my text editor to do the job :) – TeXter Aug 30 '15 at 7:22

etoolbox provides exactly this functionality via \patchcmd{<cmd>}{<search>}{<replace>}{<success>}{<failure>}, where it searches for <search> in <cmd> and replaces it with <replace>, executing <success> if the search-and-replace was successful, otherwise <failure>.

The following uses an elementary parameter passing to \patchcmd:

\documentclass{article}

\usepackage{etoolbox}

% \patchcmd{<cmd>}{<search>}{<replace>}{<success>}{<failure>}
\newcommand{\searchreplace}[3]{\patchcmd{#1}{#2}{#3}{}{}}

\begin{document}

\newcommand{\sometext}{a b c d e f g}

\sometext

\searchreplace{\sometext}{b c}{x

y}

\sometext

\end{document}


It would be advisable to also include \tracingpatches in order to make sure (via the .log) what went wrong if a patch wasn't successful.

You may run into problems with certain macros, for which your go-to alternative would be xpatch. Of course, other options also exist (using, for example, regexpatch).