python - 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 或其他任何类型。
解决方案
说到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 上查看演示。
推荐阅读
- typescript - 打字稿模板文字作为接口键
- python - Python - 无法从特定网站抓取数据 (CourseHero)
- forms - 如何更改 Drupal 8 表单元素中的选项名称?
- python - tableprint.table 仅适用于随机数
- python - 查找出现两次的模式,并且每次允许 <=2 不匹配
- javascript - Dispatch 每隔一段时间在子进程中循环使用效果
- arrays - func没有在if语句内部执行
- python - 无法在 Anaconda 上获得 tensorflow
- go - 为什么我尝试下载 go 包时不断收到此消息?
- amazon-web-services - S3 存储桶策略 - 拒绝存储桶删除返回“无效的策略语法”