首页 > 解决方案 > RegEx 匹配特定字符串中的所有匹配项

问题描述

我尝试匹配一个特定的字符串:\slash仅在给定的子字符串内(在这种情况下,在 \lstinline{}括号内):

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

所需的输出是lorem \lstinline{Foo Bar Foo} ipsum but \slash here is okay. 见https://regex101.com/r/UgKvps/1

RegEx Flavor 可以是 Python 或其他任何类型。

标签: pythonregex

解决方案


说到Python,您可以使用支持和的较新regex模块:\G\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)

这产生

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

请注意,这不适用于嵌套的乳胶命令(例如\textbf{...})。
在 regex101.com 上查看演示


推荐阅读