首页 > 解决方案 > 如何使用正则表达式删除字符串上嵌套文本周围的图案文本?

问题描述

我有一个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.'

为什么会这样,我该怎么办?

标签: pythonregexre

解决方案


您可以稍微修改自己的正则表达式以使其工作

  • 使用反向引用来替换值,而不仅仅是空字符串
  • 也让你正则表达式变得懒惰,即 (.*) -> (.*?) 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>反向引用捕获的组


推荐阅读