23

I've got a string like this: aXYbXYc, and need to replace the XY substring with a right arrow: a $\to$ b $\to$ c.

Is there any function (also provided by external packages) to help me do that?

  • Like sed? E.g., sed 's/\([a-z]\)XY/\1 $\\to$ /g' myfile.tex... – jon Mar 30 '17 at 1:51
24
\documentclass{article}
\usepackage{xstring}
\def\ReplaceStr#1{%
  \IfSubStr{#1}{XY}{%
    \StrSubstitute{#1}{XY}{$\to$}}{#1}}

\begin{document}

\ReplaceStr{aXYbXYc}

\ReplaceStr{abc}

\end{document}
| improve this answer | |
  • Please don't use minimal for examples. – cfr Mar 29 '17 at 22:43
  • What is the point in using \IfSubStr? – Solomon Ucko Jan 5 '19 at 2:36
  • I cannot remember, so I must say it is without any sense ... – user2478 Jan 5 '19 at 15:11
2
\documentclass{article}
\usepackage{listofitems}
\newcommand\substr[3]{%
  \setsepchar{#2}%
  \readlist\parsedinput{#1}%
  \foreachitem\x\in\parsedinput{%
    \ifnum\xcnt=1\else#3\fi\x%
  }%
}
\begin{document}
\substr{aXYbXYc}{XY}{$\to$}
\end{document}

enter image description here

| improve this answer | |
  • I've tried to use your \substr twice but couldn't make it work. Can you tell me what I did wrong? For instance, I added spaces in the starting string and I'd like to remove them in addition to the usual substitution. Here the code: \substr{\substr{a XY b XY c}{ }{}}{XY}{$\to$} (The result I get is: aXYbXYcc) TIA! – Stefano Bragaglia Jan 1 at 22:35
  • @StefanoBragaglia One cannot nest invocations of \substr. But in this case, one need not do so, There is an alternate invocation of \readlist (that is, \readlist*) which strips away spaces that surround the searched-for text (in this case, XY). Thus, changing \readlist to \readlist* in the definition of \substr allows for an invocation of \substr{a XY b XY c}{XY}{$\to$}, which does the desired substitution and removes the spaces. – Steven B. Segletes Jan 2 at 0:05
  • Thank you very much for the explanation! Just to add to the conversation, I was looking for a more general solution: what if I'd like to replace spaces with \quad? My own solution is using \StrSubstitute from xstring but has many limitations (to say the least). The trick they use is to set a variable on the fly: \newcommand{\subst}[1]{\StrSubstitute{#1}{XY}{$\to$}[\tempvar]\StrSubstitute{\tempvar}{ }{\quad}} – Stefano Bragaglia Jan 2 at 12:37
  • @StefanoBragaglia listofitems also can employ nested searches, which allows you to search for more than one thing at a time. Then you would use a nested \foreachitem to handle each level of the nest. – Steven B. Segletes Jan 2 at 13:56
  • listofitems seems to be very powerful! I'll study it in more details! Thanks for pointing out these details! – Stefano Bragaglia Jan 2 at 16:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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