python - 如何使用正则表达式删除字符串上嵌套文本周围的图案文本?
问题描述
我有一个txt = 'The fat \m{cat sat} on \m{the} mat.'
希望输出的文本'The fat cat sat on the mat.'
我尝试了以下两种方法:
re.sub(r'\\m\{(.*)\}', '', txt)
# output: 'The fat mat.'
re.sub(r'\\m\{(?=.*)\}', '', txt)
# output: 'The fat \\m{cat sat} on \\m{the} mat.'
为什么会这样,我该怎么办?
解决方案
您可以稍微修改自己的正则表达式以使其工作
- 使用反向引用来替换值,而不仅仅是空字符串
- 也让你正则表达式变得懒惰,即
(.*) -> (.*?) or ([^}]*)
import re
txt = 'The fat \m{cat sat} on \m{the} mat.';
r = re.sub(r'\\m\{(.*?)\}', "\g<1>", txt);
print(r);
//The fat cat sat on the mat.
注意:- 您可以使用r"\1"
or"\\1"
而不是\g<1>
反向引用捕获的组
推荐阅读
- coldfusion - 调用条带 API 时出现“条带不支持 TLS 1.0 的 HTTPS 连接”错误
- python - 尝试使用 Urllib 打开页面时出错。(python3)
- javascript - 鼠标在带有溢出 JavaScript 的容器中移动
- mercurial - Mercurial 忽略新文件
- python - 为什么会超出范围?
- java - JavaFX用滑块绘制线对齐
- c# - 在 c# 中获取更改的列宽以保存值并恢复它们
- android - 片段中的 button.setOnClickListener 不起作用
- javascript - 如何在 Qualtrics 中使用 javascript 拆分
- php - 测试时 pdo->exec 未定义