Search code examples
regexregex-lookaroundsregex-groupneovim

Regex match only if not in context


Engine: Vim RegEx

Input:

\begin{thoerm}\label{ABC_for_all}
    If the ABC is a common good, $ABC(places)$ includes everything.
\end{thorem}

We will now prove Threorem \ref{ABC_for_all}.

Expression:

(?<!(\\label|\\ref)\{\w*)ABC(?!\w*\})

Expected:

I want to match (and replace in neovim) "ABC", but only if it is not part of a name (so not in a \label{...} or \ref{...} context.

Result:

Doesn't work.

I know how to replace it if it occurs within the context:

:s/(\\label\{\w*)ABC(\w\})*/\1alphaber\2/g

But not the occurrences outside of it.

Lookahead didn't work, because the ABC may occur somewhere within the label command, thus I need variable width. I also was unable to figure out how to turn a capture group into the actual match. It seems like such a common case, but everything I found so far didn't include it.


Solution

  • Since I was told this in not possible with regex, my workaround was as follows:

    1. Rename everyhting within the specified context by some MARKER.
    2. Replace everything else.
    3. Replace the MARKER by the original.

    Each time using regex.