0

I try to match a specific string: \slash only inside a given substring (in this case inside \lstinline{} confined by brackets):

lorem \lstinline{Foo\slash Bar\slash Foo} ipsum but \slash here is okay

desired output is lorem \lstinline{Foo Bar Foo} ipsum but \slash here is okay. See https://regex101.com/r/UgKvps/1

RegEx Flavour could be Python or any other really.

Jan
  • 42,290
  • 8
  • 54
  • 79
karkraeg
  • 445
  • 4
  • 18

1 Answers1

2

Speaking of Python, you could use the newer regex module which supports \G and \K:

import regex as re

rx = re.compile(r'(?:\G(?!\A)|\\lstinline\{)[^{}]*?\K\\slash')

latex = "lorem \lstinline{Foo\slash Bar\slash Foo} ipsum but \slash here is okay"
latex = rx.sub('', latex)

print(latex)

This yields

lorem \lstinline{Foo Bar Foo} ipsum but \slash here is okay

Note that this won't work with nested latex commands (e.g. \textbf{...}).
See a demo on regex101.com.

Jan
  • 42,290
  • 8
  • 54
  • 79