2

I am looking for a regular expression which will match all occurrences of foo unless it is in a \ref{..} command. So \ref{sec:foo} should not match.

I will probably want to add more commands for which the arguments should be excluded later so the solution should be extendable in that regard.

There are some similar questions trying to detect when something is in parenthesis, etc.

The first has an interesting solution using alternatives: \(.*?\)|(,) the first alternative matches the unwanted versions and the second has the match group. However, since I am using this is in a search&replace context I cannot really use match groups.

Pumpkin
  • 233
  • 1
  • 9

1 Answers1

3

Finding a regex for what you want will need variable length look behind which is only available with very limited languages (like C# and PyPi in Python) hence you will have to settle with a less than perfect. You can use this regex to match foo that is not within curly braces as long as you don't have curly nested curly braces,

\bfoo\b(?![^{}]*})

This will not match a foo inside \ref{sec:foo} or even in somethingelse{sec:foo} as you can see it only doesn't match a foo that isn't contained in a curly braces. If you need a precise solution, then it will need variable length look behind support which as I said, is available in very limited languages.

Regex Demo

Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36