Home > Enterprise >  Find and Replace text from same Environments / Commands in Latex
Find and Replace text from same Environments / Commands in Latex

Time:09-03

I am using Overleaf to write Latex and I want to easily find and replace particular text from same environments of a Latex file.

example text,

abc xyz \a{} mno

\begin{equation}
   \a{}=a c
   \a{}=c b
\end{equation}

klm mno
\begin{equation}
   x=\a{}\times\b{}
\end{equation}
xyz mno \a{} abc

I want to replace \a{} to some other text xyz only in the equations.

text I want,

abc xyz \a{} mno

\begin{equation}
   xyz=a c
   xyz=c b
\end{equation}

klm mno
\begin{equation}
   x=xyz\times\b{}
\end{equation}
xyz mno \a{} abc

I tried many times with my little regex knowledge to match the text. Is these approaches are right?

/(?:\b(?:\\begin\{equation\})="|\G(?!\\end\{equation\}))[^}]*\K(\\a\{\})/g

and,

/(?<=\\begin\{equation\})[\s\S]*\\a\{\}[\s\S]*(?=\\end\{equation\})/gs

CodePudding user response:

No need to actually replace your macro, you could simply let latex redefine your macro inside of equations:

\documentclass{article}

\def\a{a}

\AtBeginEnvironment{equation}{\def\a{xyz}}

\begin{document}

abc xyz \a{} mno

\begin{equation}
   \a{}=a c
   \a{}=c b
\end{equation}

klm mno
\begin{equation}
   x=\a{}\times b
\end{equation}
xyz mno \a{} abc


\end{document}

CodePudding user response:

You might use a pattern like this with the /s modifier to have the dot in the pattern match any character including a newline

(?:\\begin\{equation\}|\G(?!^))(?:(?!\\a{}|\\(?:begin|end){equation}).)*\K\\a{}

Explanation

  • (?: Non capture group
    • \\begin\{equation\} Match \begin{equation}
    • | Or
    • \G(?!^) Assert the position at the end of the previous match
  • ) Close the non capture group
  • (?: Non capture group to match as a whole part
    • (?!\\a{}|\\(?:begin|end){equation}) Negative lookahead, assert that what is directly to the right of the current location is not \a{} or begin{equation} or end{equation}
    • . Match any character including a newline with the /s flag
  • )* Close the non capture group and optionally repeat it
  • \K Forget what is matched so far
  • \\a{} Match \a{}

In the replacement use xyz

See a regex demo.

  • Related